【问题标题】:Validate password follows complexity and length rules验证密码遵循复杂性和长度规则
【发布时间】:2014-05-21 06:26:39
【问题描述】:

我想使用 preg_math 函数验证输入的密码是否符合我的复杂性和长度规则:

if (!preg_match('/(?=.*[A-Za-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])/', $password)) {
    $errors[]  = 'Password allows alpha-numerical sumbols and should contain number and letters between 6-24 symbols';
}

但是这个功能不能正常工作。因为我的密码应该至少包含一个数字 (0-9) 和一个字母 (az) 符号 (,),_,- 介于 6 到 20 个符号之间。

如何编写正则表达式? 谢谢!

【问题讨论】:

  • 把它写成三个独立的测试;一个测试长度,一个测试数字,一个测试字母和符号。比将所有内容都塞进一个正则表达式要理智得多。
  • 虽然检查最小长度是明智的,但我会不做其他测试。他们只会缩小搜索空间,并惹恼用户,因此他们选择较弱的密码(如password2014)。

标签: php passwords preg-match


【解决方案1】:

您需要添加锚点并限制字符数,这是一种方法:

preg_match('/^(?=.*[A-Za-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{6,20}$/', $password)

【讨论】:

    【解决方案2】:

    您正在比较整个字符串。
    使用strpos:http://php.net/manual/en/function.strpos.php

    $password = "test!";
    //Enter characters you want to check for
    $characters = "/(!?=.*[A-Za-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])/";
    //Split into array to check each character
    $chars = str_split($characters);
    
    //Set wrong password by default and check for correct characters
    $correctPassword = false;
    
    //Check each character
    foreach($chars as $char){
        //If characters have been found, set password as correct
        if (strpos($password, $char))
        {
            $correctPassword = true;
        }
    }
    
    //Also check for length, equal or greater then 6, smaller or equal to 20
    if ( ($correctPassword) && ( strlen($password) >= 6 )  && ( strlen($password) <= 20 ) )
    {
        echo "OK";
    }
    else
    {
        echo "Password Unsafe";
    }
    

    希望这会有所帮助:)
    如果这是您搜索的答案,请标记为答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 2015-05-22
      • 2010-10-20
      相关资源
      最近更新 更多