如何使用 Jquery 限制文本框中的字母和特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24441574/
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
How to restrict alphabets and special characters in a text box using Jquery?
提问by user3154990
Can someone please show me how to restrict alphabets and special characters excluding '-' into a text box using jquery?
有人可以告诉我如何使用jquery将字母和不包括'-'的特殊字符限制到文本框中吗?
回答by RichardB
That has been answered here: Allowing only Alphanumeric values
已在此处回答: 仅允许字母数字值
You will just need to change the regex to allow for the -
您只需要更改正则表达式以允许 -
$('#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;
});
(That works, though someone more knowledgeable at regex may wish to confirm if that is the best way of adding the - to it)
(这是可行的,尽管更了解正则表达式的人可能希望确认这是否是添加 - 的最佳方式)
edit: having re-read your question, if you mean you just want to allow numbers and a dash, it is http://jsfiddle.net/HGJb3/1/
编辑:重新阅读你的问题,如果你的意思是你只想允许数字和破折号,那就是http://jsfiddle.net/HGJb3/1/
either way - ("^[a-zA-Z0-9-]+$") - that is the bit you need to play with to specify what is allowed.
无论哪种方式 - ("^[a-zA-Z0-9-]+$") - 这是您需要使用的部分来指定允许的内容。