PHP regex for password validation
Posted
by
Fabio Anselmo
on Stack Overflow
See other posts from Stack Overflow
or by Fabio Anselmo
Published on 2012-07-03T20:55:34Z
Indexed on
2012/07/03
21:15 UTC
Read the original article
Hit count: 256
I not getting the desired effect from a script. I want the password to contain A-Z, a-z, 0-9, and special chars.
- A-Z
- a-z
- 0-9 > 2
- special chars > 2
- string length >= 8
So I want to force the user to use at least 2 digits and at least 2 special chars. Ok my script works but forces me to use the digits or chars back to back. I don't want that. e.g. password testABC55$$ is valid - but i don't want that.
Instead I want test$ABC5#8 to be valid. So basically the digits/special char can be the same or diff -> but must be split up in the string.
PHP CODE:
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
$special = preg_match('#[\W]{2,}#', $password);
$length = strlen($password) >= 8;
if(!$uppercase || !$lowercase || !$number || !$special || !$length) {
$errorpw = 'Bad Password';
© Stack Overflow or respective owner