When filling a form or registering as a user we are supposed to enter passwords based on different criteria. Some request, alphanumeric entries, some require string password, while some need capital letters also. We can validate the type of strings entered using regular expressions or Laravel supported validation rules. However, when it comes to strong passwords, we should use a different approach. Let’s learn how to validate strong password inputs in the validation rule.
Laravel 8.x onwards, we can easily implement rules for a strong password without extra coding.
Validate Strong Password
Mostly, when we create a simple login we just validate for the minimum length of the user password submitted. However, to secure user account we force them to enter a password that is difficult to hint.
We can add a Password
static class with min(12)
method. This means that the password should have at least 12 minimum characters.
public function rules()
{
return [
'password' => [
'required',
Password::min(12)
],
'password_confirmation' => 'required|same:password'
];
}
This makes the user enter a password, that is longer in length. Let’s further customize our password validation rule.
Validate Password for Letters
public function rules()
{
return [
'password' => [
'required',
Password::min(12)
->letters()
],
'password_confirmation' => 'required|same:password'
];
}
The letters() function assures that the password has at least 1 letter.
Validate Password for Mixed Case Letters
To make the password have mixedCase letters we can change the letters() to mixedCase() as shown below.
'password' => [
'required',
Password::min(12)
->mixedCase()
Similarly, we can add numbers, symbols, and other functions. So the password validates if all those types are present in a password input.
The complete set of rules for a strong password with both uppercase and lowercase letters, alphanumeric, and symbols is as shown below.
public function rules()
{
return [
'email' => 'required|email:rfc,dns|unique:users,email',
'username' => 'required|unique:users,username',
'password' => [
'required',
Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
->uncompromised()
],
'password_confirmation' => 'required|same:password'
];
}
The uncompromised() function ensures that the password is not compromised on the web with a public password data breach leak.
It is also always a good idea to put a password confirmation field in your forms since the password is a masked field and the user would never know if they made a typing mistake while filling out the password.
On the backend validation, we need to use the confirmed validation rule for on password field.