简体   繁体   English

正则表达式不允许某些特殊字符

[英]Regex not allowing certain special characters

I have the following regex which does not allow certain special characters: 我有以下正则表达式,不允许某些特殊字符:

if (testString.match(/[`~,.<>;':"\/\[\]\|{}()-=_+]/)){    
    alert("password not valid");
}
else
{
    alert("password valid");
}

This is working. 这很有效。 This regex will accept a password if it does not contain any of the special characters inside the bracket (~,.<>;':"\\/\\[\\]\\|{}()-=_+) . 如果该正则表达式不包含括号内的任何特殊字符(~,.<>;':"\\/\\[\\]\\|{}()-=_+)则会接受该密码。

My problem here is it also don't allow me to input numbers which is weird. 我的问题是它也不允许我输入奇怪的数字。

Anything I missed here? 我错过了什么? Thanks in advance! 提前致谢!

Here is a sample: 这是一个示例:

jsFiddle 的jsfiddle

You've got a character range in there: )-= which includes all ASCII characters between ) and = (including numbers). 你有一个字符范围:) )-=包括之间的所有ASCII字符)= (包括数字)。 Move the - to the end of the class or escape it: 移动-到类的末尾或转义它:

/[`~,.<>;':"\/\[\]\|{}()=_+-]/

Also, you don't need to escape all of those characters: 此外,您不需要转义所有这些字符:

/[`~,.<>;':"/[\]|{}()=_+-]/

Note that in your case, it is probably enough for you, to use test instead of match : 请注意,在您的情况下,使用test而不是match可能就足够了:

if (/[`~,.<>;':"/[\]|{}()=_+-]/.test(testString))){
    ...

test returns a boolean (which is all you need), while match returns an array with all capturing groups (which you are discarding anyway). test返回一个布尔值(这是你所需要的),而match返回一个包含所有捕获组的数组(无论如何你都要丢弃)。

Note that, as Daren Thomas points out in a comment, you should rather decide which characters you want to allow . 请注意,正如Daren Thomas在评论中指出的那样,您应该决定要允许哪些字符。 Because the current approach doesn't take care of all sorts of weird Unicode characters, while complaining about some fairly standard ones like _ . 因为当前的方法不会处理各种奇怪的Unicode字符,而是抱怨像_这样的一些相当标准的字符。 To create a whitelist, you can simply invert both the character class and the condition: 要创建白名单,您可以简单地反转字符类和条件:

if (!/[^a-zA-Z0-9]/.test(testString)) {
   ...

And include all the characters you do want to allow. 并包括您想要允许的所有字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM