A new Password Rule object from Laravel 8.39

In previous versions, to define a custom validation rule, you must to implement the Illuminate\Contracts\Validation\Rule interface or use a Closure.

As below code, a custom rule StrongPassword like so.

namespace App\Rules;use Illuminate\Contracts\Validation\Rule;class StrongPassword implements Rule
{
public function passes($attribute, $value)
{
return preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@()$%^&*=_{}[\]:;\"'|\\<>,.\/~`±§+-]).{12,30}$/", $value);
}
public function message()
{
return 'The :attribute must be 12–30 characters, and include a number, a symbol, a lower and a upper case letter';
}
}

And use it in your controller or request validation.

namespace App\Http\Requests;use App\Rules\StrongPassword;
use Illuminate\Foundation\Http\FormRequest;
class AccountRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'password' => [
'required',
'confirmed',
new StrongPassword(),
],
];
}
}

From version 8.39, Nuno Maduro created a new Password Rule object in this framework with below methods:

min(): Makes minimum size of the password.
mixedCase(): Makes the password require at least one uppercase and one lowercase letter.
letters(): Makes the password require at least one letter.
numbers(): Makes the password require at least one number.
symbols(): Makes the password require at least one symbol.
uncompromised(): Ensures the password has not been compromised by checking the password against a verification API to see if the password appears in data leaks.

$request->validate([
'password' => ['required', 'confirmed', Password::min(8)->mixedCase()],
'password' => ['required', 'confirmed', Password::min(8)->letters()],
'password' => ['required', 'confirmed', Password::min(8)->numbers()],
'password' => ['required', 'confirmed', Password::min(8)->symbols()],
'password' => ['required', 'confirmed', Password::min(8)->uncompromised()],
]);

Or you can use them all combined like so.

$request->validate([
'password' => ['required', 'confirmed', Password::min(8)
->mixedCase()
->letters()
->numbers()
->symbols()
->uncompromised(),
],
]);

Thanks Nuno Maduro.

Reference: https://github.com/laravel/framework/pull/36960

Full-Stack web developer.