jquery - 验证按键上的字符?

Twi*_*Kit 28 validation jquery keypress

我有一个表单文本字段,我想只允许数字和字母.(即,没有#$!等等...)有没有办法抛出错误,防止按键实际输出任何东西,如果用户尝试使用除数字和字母之外的任何字符?我一直试图找一个插件,但还没有找到任何能做到这一点的东西......

use*_*716 35

$('input').keyup(function() {
    var $th = $(this);
    $th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.'); return ''; } ) );
});
Run Code Online (Sandbox Code Playgroud)

编辑:

这里有一些其他好的答案可以防止输入发生.

我已经更新了我的,因为你也想显示一个错误.替换可以使用函数而不是字符串.该函数运行并返回一个替换值.我添加了一个alert来显示错误.

http://jsfiddle.net/ntywf/2/


Jur*_*riy 11

那么patrick的答案会删除字符,如果它是错误的,实际上是防止将字符插入到字段使用中

$("#field").keypress(function(e) {
    // Check if the value of the input is valid
    if (!valid)
        e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

这样这封信就不会来到textarea


Thi*_*ter 10

$('#yourfield').keydown(function(e) {
    // Check e.keyCode and return false if you want to block the entered character.
});
Run Code Online (Sandbox Code Playgroud)


Bra*_*ath 6

我发现在keypress和keyup上结合验证可以得到最好的结果.如果要处理复制粘贴文本,则必须启用密钥.如果跨浏览器问题允许非数字值进入文本框,这也是一个问题.

    $("#ZipCode").keypress(function (event) {

        var key = event.which || event.keyCode; //use event.which if it's truthy, and default to keyCode otherwise

        // Allow: backspace, delete, tab, and enter
        var controlKeys = [8, 9, 13];
        //for mozilla these are arrow keys
        if ($.browser.mozilla) controlKeys = controlKeys.concat([37, 38, 39, 40]);

        // Ctrl+ anything or one of the conttrolKeys is valid
        var isControlKey = event.ctrlKey || controlKeys.join(",").match(new RegExp(key));

        if (isControlKey) {return;}

        // stop current key press if it's not a number
        if (!(48 <= key && key <= 57)) {
            event.preventDefault();
            return;
        }
    });

$('#ZipCode').keyup(function () {
    //to allow decimals,use/[^0-9\.]/g 
    var regex = new RegExp(/[^0-9]/g);
    var containsNonNumeric = this.value.match(regex);
    if (containsNonNumeric)
        this.value = this.value.replace(regex, '');
});
Run Code Online (Sandbox Code Playgroud)