0

我有一个用于注册过程的密码验证脚本,如果我没有设置最大长度限制,它可以正常工作。如果我添加最大限制为 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.";
        }

请在降级之前让我知道,以便我可以编辑我的问题。谢谢!

4

4 回答 4

4

要限制长度,只需编辑您的正则表达式。你已经成功了一半。

/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,32}$/

演示:http ://regex101.com/r/nK5yY6

于 2013-09-12T08:48:39.650 回答
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.";
}
于 2013-09-12T08:50:49.250 回答
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.";
    }
于 2013-09-12T08:45:59.950 回答
0

如果您正在寻找至少 1 个数字和 1 个字母的密码,请尝试以下操作:

^.*(?=.{8,32})(?=.*\d)(?=.*[a-zA-Z]).*$
于 2013-09-12T08:51:08.723 回答