使用此PHP正则表达式进行密码验证有什么问题? [英] What is wrong with this PHP regex to do password validation?
本文介绍了使用此PHP正则表达式进行密码验证有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ereg("/^(?=.*[a-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])(?=.*[A-Z]).{7,19}$/","ABCabc123!!");
这应该是一个密码验证器,要求大小写字母以及特殊字符和最小长度为8的数字.但是上面的返回false.我在做什么错了?
This is supposed to be a password validator, requiring alphabets in upper and lowercases along with numbers special chars and mininmum length of 8....but the above returns false. What am I doing wrong?
推荐答案
请改用preg_*
和更好的验证字符串
您正在使用的正则表达式至少有3个问题:
Use preg_*
instead, and a better validation string
There are (at least) 3 issues with the regex you're using:
- 当有更好的选择-
[\W_]
时,您当前不需要检查(?=.*[^a-zA-Z0-9])
. - 您要检查的字符至少为
7
个,且不超过19
个,而不是至少为8
个. - 您正在使用不推荐使用的功能.
- 您的功能允许在密码中使用空格.
- You're currently needlessly checking for
(?=.*[^a-zA-Z0-9])
when there is a better option to do this -[\W_]
. - You're checking for at least
7
characters and no more than19
, rather than at least8
. - You're using a deprecated function.
- Your function allows whitespace in passwords.
这应该对您更好:
$regex = "/^\S*(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W_])(?=\S{8,})\S*$/";
$valid = (bool) preg_match($regex,$password);
此正则表达式的组成部分的解释:
Explanation of the components of this regex:
/ Delimiter
^ Start of string anchor
\S* Any string without whitespace
(?=\S*[a-z]) Must contain at least 1 lowercase letter
(?=\S*[A-Z]) Must contain at least 1 uppercase letter
(?=\S*[\d]) Must contain at least 1 digit
(?=\S*[\W_]) Must contain at least 1 special character
(note: \W will not consider underscore '_' a special character)
(?=\S{8,}) Must contain at least 8 characters
$ End of string anchor
正如安迪·莱斯特(Andy Lester)所指出的,多次检查可能会更好
正如安迪(Andy)所言,最好不要存储一堆规则.这使您可以定制错误消息并轻松添加规则.在PHP中,我可以这样实现:
As Andy mentioned, you're best off storing a bunch of rules. This allows you to tailor your error messages and add rules easily. In PHP I'd implement this in this way:
function validatePassword($password) {
$rules = array(
'no_whitespace' => '/^\S*$/',
'match_upper' => '/[A-Z]/',
'match_lower' => '/[a-z]/',
'match_number' => '/\d/',
'match_special' => '/[\W_]/',
'length_abv_8' => '/\S{8,}/'
);
$valid = true;
foreach($rules as $rule) {
$valid = $valid && (bool) preg_match($rule, $password);
if($valid !== true) break;
}
return (bool) $valid;
}
可以在此处找到现场演示.
这篇关于使用此PHP正则表达式进行密码验证有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文