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

后端 未结 9 950
耶瑟儿~
耶瑟儿~ 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:34

    I've done this with my drupal custom form in hook_form_validate here the password should be 6 characters of letters, numbers and at least one special character.

    <?
    if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])(?=.*[!@#$%])[0-9A-Za-z!@#$%]{6,15}$/', $form_state['values']['pass'])) {
        form_set_error('pass', t('Password must contain 6 characters of letters, numbers and at least one special character.'));
    }
    ?>
    
    0 讨论(0)
  • 2020-12-04 23:39
    preg_match('/^(?=.*\d)(?=.*[@#\-_$%^&+=§!\?])(?=.*[a-z])(?=.*[A-Z])[0-9A-Za-z@#\-_$%^&+=§!\?]{8,20}$/',$password)
    
    • at least one lowercase char
    • at least one uppercase char
    • at least one digit
    • at least one special sign of @#-_$%^&+=§!?
    0 讨论(0)
  • 2020-12-04 23:40

    I liked r3bel's answer, so I had a play with it and ended up with the following as a password-checking function:

    function password_strength_check($password, $min_len = 8, $max_len = 70, $req_digit = 1, $req_lower = 1, $req_upper = 1, $req_symbol = 1) {
        // Build regex string depending on requirements for the password
        $regex = '/^';
        if ($req_digit == 1) { $regex .= '(?=.*\d)'; }              // Match at least 1 digit
        if ($req_lower == 1) { $regex .= '(?=.*[a-z])'; }           // Match at least 1 lowercase letter
        if ($req_upper == 1) { $regex .= '(?=.*[A-Z])'; }           // Match at least 1 uppercase letter
        if ($req_symbol == 1) { $regex .= '(?=.*[^a-zA-Z\d])'; }    // Match at least 1 character that is none of the above
        $regex .= '.{' . $min_len . ',' . $max_len . '}$/';
    
        if(preg_match($regex, $password)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    

    Max/Min lengths are default or adjustable, each requirement is default on, but can be switched off, and I wanted to support any symbols so the last requirement is "anything that isn't one of the above types", rather than a fixed set of symbols.

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