jquery - 验证按键上的字符?

时间:2010-05-11 16:39:25

标签: jquery validation keypress

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

7 个答案:

答案 0 :(得分: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 ''; } ) );
});

修改

这里有一些其他好的答案可以阻止输入。

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

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

答案 1 :(得分:11)

帕特里克的答案如果错误就会删除字符,实际阻止字符插入字段使用

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

这样信就不会来到textarea

答案 2 :(得分:10)

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

答案 3 :(得分: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, '');
});

答案 4 :(得分:0)

你可以试试这个扩展名:

jQuery.fn.ForceAlphaNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, letters, numbers and keypad numbers ONLY
            return (
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 65 && key <= 90) ||
                (key >= 96 && key <= 105));
        })
    })
};

用途:

$("#yourInput").ForceAlphaNumericOnly();

答案 5 :(得分:0)

上面的jquery扩展(ForceAlphaNumericOnly)很好,但仍然可以通过!@#$%^&*()

允许以下字符

在我的Mac上,当您按 shift 键(键码16)然后 1 时,它会输入!,但键码是491的密码。

答案 6 :(得分:0)

$(document).ready(function() {
 $('.ipFilter').keydown((e) => {
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true) || 
          e.keyCode === 67 && (e.ctrlKey === true || e.metaKey === true) ||
          e.keyCode === 86 && (e.ctrlKey === true || e.metaKey === true) ||
          e.keyCode === 82 && (e.ctrlKey === true || e.metaKey === true)) || 
        (e.keyCode >= 35 && e.keyCode <= 40 )) {
             return;
    }
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
  });
});