且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JavaScript仅允许HTML输入中的特定字符

更新时间:2022-11-26 19:13:38

您可以使用正则表达式将用户限制为仅输入数字和短划线。使用正则表达式的优势在于用户可以更自然地与输入进行交互,例如,他们可以粘贴到文本输入中,并且将成功验证:

You can use regex to limit the user to only inputting numbers and dashes. Using regex has the advantage that users can more naturally interact with the input, for instance they can paste into the text input and it will be validated successfully:

//bind event handler to the `keyup` event so the value will have been changed
$('.SSNTB').on('keyup', function (event) {

    //get the newly changed value and limit it to numbers and hyphens
    var newValue = this.value.replace(/[^0-9\-]/gi, '');

    //if the new value has changed, meaning invalid characters have been removed, then update the value
    if (this.value != newValue) {
        this.value = newValue;
    }
}).on('blur', function () {

    //run some regex when the user un-focuses the input, this checks for the number ninteen or twenty, then a dash, three numbers, a dash, then four numbers
    if (this.value.search(/[(20)(19)](-)([0-9]{3})(-)([0-9]{4})/gi) == -1) {
        alert('ERROR!');
    } else {
        alert('GOOD GOING!');
    }
});

这是一个演示: http://jsfiddle.net/BRewB/2/

请注意 .on( )是jQuery 1.7中的新功能,在这种情况下与使用 .bind()相同。

Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().