When the user provides their account password, it is always recommended to validate the input. Password strength validation is very useful to check whether the password is strong. A strong password makes the user’s account secure and helps to prevent account hacking.
Using Regex (Regular Expression), you can easily validate the password strength in PHP. In the example code, we will show you how to check password strength and validate a strong password in PHP using Regex.
The following code snippet validates the password using preg_match() function in PHP with Regular Expression, to check whether it is strong and difficult to guess.
// Given password
$password = 'user-input-pass';
// Validate password strength
$uppercase = preg_match('@[A-Z]@', $password);
$lowercase = preg_match('@[a-z]@', $password);
$number = preg_match('@[0-9]@', $password);
$specialChars = preg_match('@[^\w]@', $password);
if(!$uppercase || !$lowercase || !$number || !$specialChars || strlen($password) < 8) {
echo 'Password should be at least 8 characters in length and should include at least one upper case letter, one number, and one special character.';
}else{
echo 'Strong password.';
}
Excellent validation:)
Awesome
Perfect
Awesome – thank you!!
This helped me A LOT! Thank!
Simple and perfect!
Thank you for this. It will help me with my upcoming project
Perfectly correct
Nice!
I do have a question, though…what are the at symbols (@) doing? I’ve been looking everywhere and can’t seem to find their purpose in regular expressions…
Just what I needed! Thanks
perfect and very clear coding
nice