jQuery - 在按键时验证字符?

28

我有一个表单文本框,我只想允许输入数字和字母(例如,不允许 #$! 等字符)。 是否有一种方法可以在用户尝试输入数字和字母以外的任何字符时弹出错误并防止按键实际输出任何内容? 我一直在寻找插件,但没有真正找到能做到这一点的插件...


很相似于:https://dev59.com/eHNA5IYBdhLWcg3wWseK - ThiefMaster
这不会阻止非字母数字字符通过上下文菜单(右键单击并粘贴)被粘贴进来。在http://jsfiddle.net/ntywf上试试看。 - Janek Bogucki
这是一个非常流畅的插件:http://digitalbush.com/projects/masked-input-plugin/ - meo
7个回答

38
$('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
+1的效果很好。http://jsfiddle.net/ntywf/ 尽管我有一种感觉,原帖作者可能也想允许空格。 - karim79
@karim79 - 感谢你添加了jsfiddle。我应该经常这样做的。 - user113716
它会阻止必要的命令,如上下箭头、Shift和Ctrl操作。如何控制它。 - VIVEK MISHRA

11

嗯,Patrick的答案会删除字符,如果要真正“防止”字符被插入到字段中,请使用

$("#field").keypress(function(e) {
    // Check if the value of the input is valid
    if (!valid)
        e.preventDefault();
});
这样信件就不会出现在文本区域内。

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

7

我发现在按键和松开键时进行验证可以得到最好的结果。如果您想处理复制粘贴的文本,则必须使用松开键。此外,如果存在跨浏览器问题允许非数字值进入您的文本框,则它也是一个万无一失的选择。

    $("#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, '');
});

1
在Chrome中,粘贴(ctrl-v)时,keyup似乎对this.value没有任何值,因此正则表达式永远不匹配。在Firefox中,我观察到End、Delete、Home、Page Up和Page Down在该字段中无法工作。 - peater

1
你可以尝试使用这个扩展:
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();

我刚想到了这个解决方案:如果你从缓冲区插入文本可能会有问题。如果用户按下ctrl+v,他希望将自己的文本插入字段中(如果它有效)。这种方法可能无法处理这种情况。不过还需要测试一下。 - Juriy

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();
    }
  });
});

0

上述的jQuery扩展(ForceAlphaNumericOnly)很好,但仍然允许以下字符通过!@#$%^&*()

在我的Mac上,当您按下shift键(keycode 16),然后按1,它会输入!,但keycode是49,即1的keycode。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接