Use preg_*
instead, and a better validation string
There are (at least) 3 issues with the regex you're using:
- You're currently needlessly checking for
(?=.*[^a-zA-Z0-9])
when there is a better option to do this - [\W_]
.
- You're checking for at least
7
characters and no more than 19
, rather than at least 8
.
- You're using a deprecated function.
- Your function allows whitespace in passwords.
This should work better for you:
$regex = "/^\S*(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W_])(?=\S{8,})\S*$/";
$valid = (bool) preg_match($regex,$password);
Explanation of the components of this regex:
/ Delimiter
^ Start of string anchor
\S* Any string without whitespace
(?=\S*[a-z]) Must contain at least 1 lowercase letter
(?=\S*[A-Z]) Must contain at least 1 uppercase letter
(?=\S*[\d]) Must contain at least 1 digit
(?=\S*[\W_]) Must contain at least 1 special character
(note: \W will not consider underscore '_' a special character)
(?=\S{8,}) Must contain at least 8 characters
$ End of string anchor
As pointed out by Andy Lester, you may be better off with multiple checks
As Andy mentioned, you're best off storing a bunch of rules. This allows you to tailor your error messages and add rules easily. In PHP I'd implement this in this way:
function validatePassword($password) {
$rules = array(
'no_whitespace' => '/^\S*$/',
'match_upper' => '/[A-Z]/',
'match_lower' => '/[a-z]/',
'match_number' => '/\d/',
'match_special' => '/[\W_]/',
'length_abv_8' => '/\S{8,}/'
);
$valid = true;
foreach($rules as $rule) {
$valid = $valid && (bool) preg_match($rule, $password);
if($valid !== true) break;
}
return (bool) $valid;
}
Live demonstration can be found here.