This question already has an answer here:
I am trying to establish password parameters to be 8-20 characters long, at least one upper case character, number, and symbol. I have written the code as such
(preg_match ('/^(\W+)(\d+)([A-Z]+)([a-z]+){8,20}$/', $_POST['pass1']) )
My interpretation of my code is as follows:
W+ one or more symbols (non alpha numeric)
d+ one or more numbers
[A-Z]+ one or more uppercase characters
[a-z]+ one or more lower case characters
{8,20} string length min 8 max 20
When I enter the password as Anyhelp4me! I get an invalid password message. What are your suggestions.
</div>
Don't do it all with one regex. It will be far more maintainable, understandable, and easier to change in the future if you make multiple calls to preg_match with multiple regexes.
$password_is_ok =
preg_match( '/\W/', $pass ) &&
preg_match( '/\d/', $pass ) &&
preg_match( '/[a-z]/', $pass ) &&
preg_match( '/[A-Z]/', $pass ) &&
strlen( $pass ) >= 8 &&
strlen( $pass ) <= 20;
That is far more readable and understandable by the next person who has to read your code (who might be you) than any single-regex monstrosity you can concoct.
Okay...I tried the previous recommendation and it only imposed the "8,10" restriction. I found this on stackoverflow "Create preg_match for password validation allowing (!@#$%)" and modified the code presented in that response as follows:
/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*\W)[0-9A-Za-z!@#$%]{8,20}$/
I have tested it several times and it does work. You have to have at least one digit, one uppercase, one lower case and a specified symbol (!@#$%) and between 8 and 20 characters.