仅允许字母数字值 [英] Allowing only Alphanumeric values
问题描述
可能重复:
如何防止用户输入无效字符在输入字段中
Possible Duplicate:
How to prevent users from entering invalid characters inside an input field
我在页面上有3个文本框.其中一个应该允许数字,其他字母和第三个字母可以是数字或字母.
I have 3 textboxes on a page. One of them should allows numbers, the other alphabets and the 3rd either numbers or alphabets.
因为这是唯一的要求,所以我不想使用验证插件或任何其他第三方插件.如何通过使用纯jQuery创建自己的插件来做到这一点?
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?
这是我所做的,但是我感觉代码太长了
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));
});
谁能告诉我哪种方法是解决此问题的最佳方法?
Can anyone tell me which si the best way to approach this issue?
推荐答案
更好的解决方案可能是使用基于正则表达式的检查.下面的示例将在ID为text
的字段中仅限制字母数字字符:
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
:
$('#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;
});
这篇关于仅允许字母数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!