jQuery 仅允许字母数字值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13236651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:24:59  来源:igfitidea点击:

Allowing only Alphanumeric values

jquery

提问by KayKay

Possible Duplicate:
How to prevent users from entering invalid characters inside an input field

可能的重复:
如何防止用户在输入字段中输入无效字符

I have 3 textboxes on a page. One of them should allows numbers, the other alphabets and the 3rd either numbers or alphabets.

我在页面上有 3 个文本框。其中之一应该允许数字,其他字母和第三个数字或字母。

Since this is the only requirement, I do not want to use the validation plugin, or any other 3rd party plugin. How can I do this by creating my own plugin using pure jQuery?

由于这是唯一的要求,我不想使用验证插件或任何其他 3rd 方插件。我如何通过使用纯 jQuery 创建我自己的插件来做到这一点?

This is what I have done but I get a feeling that the code will become too long

这就是我所做的,但我觉得代码会变得太长

 $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;            
            return (
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        });

http://jsfiddle.net/Cvus8/

http://jsfiddle.net/Cvus8/

Can anyone tell me which si the best way to approach this issue?

谁能告诉我哪个是解决这个问题的最佳方法?

回答by Kami

The better solution might be to go with regular expression based checks. Example below will limit only alphanumeric characters in the field with id text:

更好的解决方案可能是使用基于正则表达式的检查。下面的示例将仅限制带有 id 的字段中的字母数字字符text

$('#text').keypress(function (e) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }

    e.preventDefault();
    return false;
});

回答by Scorpio

A digit in the range 1-9 followed by zero or more other digits:

1-9 范围内的数字后跟零个或多个其他数字:

^[1-9]\d*$

Ensure that a string only contains (ASCII) alphanumeric characters, underscores and spaces

确保字符串仅包含 (ASCII) 字母数字字符、下划线和空格

^[\w ]+$

Only Alphabets no space or _

只有字母没有空格或_

^[a-zA-Z]+$

To match a string that contains only those characters (or an empty string), try

要匹配仅包含这些字符(或空字符串)的字符串,请尝试

^[a-zA-Z0-9_]*$

Some patterns that may help ..but I think you will have to modify them as per your need..I hope it help ..

一些可能有帮助的模式......但我认为你必须根据你的需要修改它们......我希望它有帮助......