[英]Regex for simple password validation in PHP and Javascript
I'm trying to validate a password with PHP and I want to use the same Regex with Javascript, In my PHP I'm getting error when I'm trying to use the following regex. 我正在尝试使用PHP验证密码,并且希望将相同的Regex与Javascript一起使用。在我的PHP中,尝试使用以下正则表达式时出现错误。 (Warning: filter_var(): Compilation failed: range out of order in character class at offset 14)
/^[a-zA-Z0-9_-\]\[\?\/<~#`!@\$%\^&\*\(\)\+=\}\|:\";\',>\{]{4,20}$/
if (!filter_var($password,FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z0-9_-\]\[\?\/<~#`!@\$%\^&\*\(\)\+=\}\|:\";\',>\{]{4,20}$/")))){
$errors .= "Please enter a valid password.";
}
I want the password to have 0-9
, a-zA-Z
and these characters ] [ ? / < ~ # ! @ $ % ^ & * ( ) + = } | : " ; ' , > { space
我希望密码具有0-9
, a-zA-Z
和这些字符] [ ? / < ~ # ! @ $ % ^ & * ( ) + = } | : " ; ' , > { space
] [ ? / < ~ # ! @ $ % ^ & * ( ) + = } | : " ; ' , > { space
] [ ? / < ~ # ! @ $ % ^ & * ( ) + = } | : " ; ' , > { space
plus ` ] [ ? / < ~ # ! @ $ % ^ & * ( ) + = } | : " ; ' , > { space
格加`
I want to use the regex for front and back ends. 我想将正则表达式用于前端和后端。
Take a look at this "modular" regEx 看看这个“模块化” regEx
/(?=.*\\d)(?=.*[az])(?=.*[AZ]).{8,}/.test(password)
this password should have: 该密码应具有:
(?=.*\\d)
= digits (?=.*\\d)
=数字 (?=.*[az])
= small letters (?=.*[az])
=小写字母 (?=.*[AZ])
= cap. (?=.*[AZ])
=上限。 letters 信 .{8,}
= at least 8 chars long .{8,}
=至少8个字符 Special chars part: taken from one of the answers above thanks @stribizhev 特殊字符部分:摘自上述答案之一,感谢@stribizhev
(?=.*[?\\/<~#`!@$%^&*()+=}|:\\";\\',>{ -])
= special chars (?=.*[?\\/<~#`!@$%^&*()+=}|:\\";\\',>{ -])
=特殊字符 So you end up with: 因此,您最终得到:
/(?=.*\\d)(?=.*[az])(?=.*[AZ])(?=.*[?\\/<~#`!@$%^&*()+=}|:\\";\\',>{ -])/.test(password)
to force minimal lenght .{n,} n = lenght 强制最小长度。{n,} n =长度
/(?=.*\\d)(?=.*[az])(?=.*[AZ])(?=.*[?\\/<~#`!@$%^&*()+=}|:\\";\\',>{ -]).{8,}/.test(pass)
/^[a-zA-Z0-9_\]\[\?\/\<\~\#\`\@\$%\^&\*\(\)\+=\}\|:\";\'\,>\{]{4,20}$/
You had an un-escaped hyphen in your first character set, and you needed to escape the comma. 您的第一个字符集中有一个未转义的连字符,并且需要转义逗号。
Edit: Escaped a few other metacharacters. 编辑:转义了其他几个元字符。
You can use 您可以使用
^[a-zA-Z0-9_\]\[?\/<~#`!@$%^&*()+=}|:\";\',>{ -]{4,20}$
^^
Note the "smart" position of the hyphen at the end of the character class, and in JS and PHP you won't have to escape it. 注意字符类末尾的连字符的“智能”位置,在JS和PHP中,您不必转义。
I see your regex is missing a space, I added it, too. 我看到您的正则表达式缺少空格,我也添加了它。
Note that inside a character class, a lot of special characters are treated as literals, and do not have to be escaped. 请注意,在字符类内部,许多特殊字符被视为文字,不必进行转义。 I removed escape symbols from those that do not need escaping. 我从不需要转义的符号中删除了转义符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.