Javascript 如何使用正则表达式检查用户输入是否仅包含特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3649583/
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 use regex to check that user input does not consist of special characters only?
提问by Arko
How to put a validation over a field which wouldn't allow only special characters, that means AB#,A89@,@#ASDis allowed but @#$^&or #is not allowed. I need the RegEx for this validation.
如何把验证过的字段,它不会只允许特殊字符,这意味着AB#,A89@,@#ASD被允许的,但@#$^&还是#不允许。我需要此验证的 RegEx。
回答by Yanick Rochon
str.match(/^[A-Z#@,]+$/)
will match a string that...
将匹配一个字符串...
- ... starts
^and ends$with the enclosed pattern - ... contains any upper case letters
A-Z(will not match lower case letters) - ... contains only the special chars
#,@, and, - ... has at least 1 character (no empty string)
- ... 以封闭模式开始
^和结束$ - ... 包含任何大写字母
A-Z(不匹配小写字母) - ... 只包含特殊字符
#,@, 和, - ... 至少有 1 个字符(无空字符串)
For case insensitive, you can add iat the end : (i.g. /pattern/i)
对于不区分大小写的,您可以i在末尾添加:(ig /pattern/i)
** UPDATE**
**更新**
If you need to validate if the field contains only specials characters, you can check if the string contains only characters that are not words or numbers :
如果您需要验证字段是否仅包含特殊字符,您可以检查字符串是否仅包含不是单词或数字的字符:
if (str.match(/^[^A-Z0-9]*$/i)) {
alert('Invalid');
} else {
alert('Valid');
}
This will match a string which contains only non-alphanumeric characters. An empty string will also yield invalid. Replace *with +to allow empty strings to be valid.
这将匹配仅包含非字母数字字符的字符串。空字符串也将产生无效。替换*为+以允许空字符串有效。
回答by Tim Pietzcker
If you can use a "negative match" for your validation, i. e. the input is OK if the regex does notmatch, then I suggest
如果你可以使用一个“消极比赛”为您的验证,即输入是确定的,如果正则表达式并没有匹配,那么我建议
^\W*$
This will match a string that consists only of non-word characters (or the empty string).
这将匹配仅包含非单词字符(或空字符串)的字符串。
If you need a positive match, then use
如果您需要正匹配,请使用
^\W*\w.*$
This will match if there is at least one alphanumeric character in the string.
如果字符串中至少有一个字母数字字符,这将匹配。
回答by mpen
I believe what you're looking for is something like this:
我相信你正在寻找的是这样的:
!str.match(/^[@#$^&]*$/)
Checks that the string does notcontain onlysymbols, i.e., it contains at least one character that isn'ta symbol.
检查该字符串并没有包含唯一的符号,即它至少包含一个字符不是一个符号。

