Create preg_match for password validation allowing (!@#$%)

后端 未结 9 949
耶瑟儿~
耶瑟儿~ 2020-12-04 23:14

I would like to create a preg_match function to validate my passowrds, but I\'m not sure how to write it to allow the following special characters to be used: <

相关标签:
9条回答
  • 2020-12-04 23:26

    A different way

    Let look different to this, I believe that users can use all of the ASCII valid characters (32 < ascii_code < 127) in the password and created a function that checks all the characters that are is in ASCII table!

    function check($pass, $i = 0){
         if(strlen($pass) > $i)
             return (0rd(pass[$i]) > 32 and 0rd(pass[$i]) < 127) and check($pass, $i + 1);
    }
    

    Usage

    if(!check($_POST["password"])){
        echo "password is wrong";
    }
    
    0 讨论(0)
  • 2020-12-04 23:31

    I think this should look like that:

    if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,12}$/', $password)) {
        echo 'the password does not meet the requirements!';
    }
    

    Between start -> ^
    And end -> $
    of the string there has to be at least one number -> (?=.*\d)
    and at least one letter -> (?=.*[A-Za-z])
    and it has to be a number, a letter or one of the following: !@#$% -> [0-9A-Za-z!@#$%]
    and there have to be 8-12 characters -> {8,12}

    As user557846 commented to your question, I would also suggest you to allow more characters, I usually (if i use a maximum) take at least 50 :)

    btw, you might want to take a look at this regex tutorial

    0 讨论(0)
  • 2020-12-04 23:32
    if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])(?=.*[!@#$%])[0-9A-Za-z!@#$%]
    {6,15}$/',($_POST['password']))) {
        $message='Password must contain 6 characters of letters, numbers and 
        at least one special character.';
    }
    
    0 讨论(0)
  • 2020-12-04 23:32

    Look up character classes, a basic feature of regular expressions.

    0 讨论(0)
  • 2020-12-04 23:32
    if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,12}$/', $password)) {
        echo 'the password does not meet the requirements!';
        }
    

    In the above statement.. what possible password thus exist?.

    0 讨论(0)
  • 2020-12-04 23:33

    I have developed a complete regex for a bit more complex check

    /^(?=.*\d)(?=.*[A-Za-z])(?=.*[A-Z])(?=.*[a-z])(?=.*[ !#$%&'\(\) * +,-.\/[\\] ^ _`{|}~\"])[0-9A-Za-z !#$%&'\(\) * +,-.\/[\\] ^ _`{|}~\"]{8,50}$/
    

    Basically I check for the password to have 1 digit, 1 capital, 1 lower and 1 special character. I hope this helps someone looking for a regex.

    0 讨论(0)
提交回复
热议问题