Password regex PHP

Password

Password regular expression can be used to verify that a password provided is strong enough to provide better protection against bot brute force attacks. This method, however, does not guarantee that a password will have enough entropy to be completely safe.

Strong password regex

The regular expression below cheks that a password:

  • Has minimum 8 characters in length. Adjust it by modifying {8,}
  • At least one uppercase English letter. You can remove this condition by removing (?=.*?[A-Z])
  • At least one lowercase English letter.  You can remove this condition by removing (?=.*?[a-z])
  • At least one digit. You can remove this condition by removing (?=.*?[0-9])
  • At least one special character,  You can remove this condition by removing (?=.*?[#?!@$%^&*-])
"/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/"

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Example code in PHP:

// Validate strong password
$password_regex = "/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/"; 
echo preg_match($password_regex, 'secret'); // returns 0
echo preg_match($password_regex, '-Secr3t.'); // returns 1

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Notes on password regex validation

While this regex validation is better than nothing, in situations when additional security is needed you should also check the password entered for a set of commonly used passwords like:

  • .Qwerty1
  • !Q1w2e3r4
  • etc

One good list can be found here.