Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 14, 2021 03:38 am GMT

A new Password Rule object from Laravel8.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 1230 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


Original Link: https://dev.to/vumanhtrung/a-new-password-rule-object-from-laravel-8-39-5cil

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To