我有一个用于注册过程的密码验证脚本,如果我没有设置最大长度限制,它就可以正常工作。如果我添加最大限制为32,则忽略验证,即使我有超过32个字符,也会创建帐户。
工作脚本:
if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["password"]) === 0)
{
echo "The password must contain lower case characters, upper case characters and numbers. It's length should be between 8 and 32 characters.";
}
不工作的脚本:
if (preg_match("/^.*(?=.{8,32})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["password"]) === 0)
{
echo "The password must contain lower case characters, upper case characters and numbers. It's length should be between 8 and 32 characters.";
}
敬礼之前请告诉我,以便我可以编辑我的问题。谢谢!
答案 0 :(得分:4)
要限制长度,只需编辑正则表达式即可。你已经到了一半了。
/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,32}$/
答案 1 :(得分:2)
在一个大的正则表达式中执行它是一个代码维护的噩梦。拆分它对于查看代码的其他人来说要容易得多,它还允许您提供更具体的错误消息。
此解决方案适用于我,请尝试:
$password = $_POST["password"];
$uppercase = preg_match('@[A-Z]@', $password);
$lowercase = preg_match('@[a-z]@', $password);
$number = preg_match('@[0-9]@', $password);
$length = preg_match("@^.{8,32}$@" , $password);
if(!$uppercase || !$lowercase || !$number || !$length ) {
echo "The password must contain lower case characters, upper case characters and numbers. It's length should be between 8 and 32 characters.";
}
答案 2 :(得分:1)
if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["password"]) === 0 || strlen($_POST['password']) < 8 || strlen($_POST['password']) > 32 )
{
echo "The password must contain lower case characters, upper case characters and numbers. It's length should be between 8 and 32 characters.";
}
答案 3 :(得分:0)
如果您要查找至少1位数和1位字母的密码,请尝试以下操作:
^.*(?=.{8,32})(?=.*\d)(?=.*[a-zA-Z]).*$