如何使用jQuery仅允许定义的字符作为输入?

net*_*ser 1

如何允许特殊字符,如连字符,逗号,斜杠,空格键,退格键,删除键以及字母数字值,并限制jQuery中的其余部分?

由于此标准(允许的字符/输入值)因字段而异,我想将其作为一种实用方法,它接受输入字段id和允许的字符作为参数.例如:limitCharacters(textid,pattern)

Dav*_*ing 6

您可以检查keyCode keydown并运行preventDefault()匹配:

$(\'input\').keydown(function(e) {\n    if (e.which == 8) { // 8 is backspace\n        e.preventDefault();\n    }\n});\xe2\x80\x8b\n
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/GVb6L/

如果您需要限制某些字符和键码+使其成为jQuery插件,请尝试以下方法:

$.fn.restrict = function( chars ) {\n    return this.keydown(function(e) {\n        var found = false, i = -1;\n        while(chars[++i] && !found) {\n            found = chars[i] == String.fromCharCode(e.which).toLowerCase() || \n                    chars[i] == e.which;\n        }\n        found || e.preventDefault();\n    });\n};\n\n$(\'input\').restrict([\'a\',8,\'b\']);\xe2\x80\x8b\n
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/DHCUg/