开发者

"Intercepting" user input into text box and removing it

I have a text box that I would like to do some validation on. At the moment I have this code:

function updateChanger() {

    // Validate input
    var likeMessage = validateInput($("#like").val());

    alert(likeMessage);
}

function validateInput(input) {
    input = input.replace(/[^a-zA-Z0-9:\(\/\)\s\.,!~]/g, "");
    return input;
}

This successfully trims out unwanted characters in the likeMessage variable, but the character still gets entered into the text box. I would like to stop that from happening.

I know it will have something to do with $("#like").val() but the only thing I can think of is just chopping off the end character from the text开发者_高级运维 box value, would this suffice?

Thanks for any help!


You can do it using the keyup event, like this:

$("#like").keyup(function() {
  $(this).val($(this).val().replace(/[^a-zA-Z0-9:\(\/\)\s\.,!~]/g, ""));
});

This checks for and removes invalid characters every time they key lets up, so the invalid character won't ever be left in the box, it gets removed immediately.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜