How to Validate Weak and Strong Passwords in Laravel

 How to Validate Weak and Strong Passwords in Laravel

How to Validate Weak and Strong Passwords in Laravel

When building secure applications, ensuring users create strong passwords is crucial. In Laravel, validating passwords is straightforward thanks to its flexible validation rules. This blog will guide you on validating passwords for strength and how to warn users if they enter weak ones.

To implement this we will create a custom rule class to write our custom validation logic. Let's implement this.

Create a Rule class :

Create a rule class using following command and implement your password validation logic accordingly.

php artisan make:rule StrongPassword

StrongPassword.php :

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class StrongPassword implements ValidationRule
{
    public function passes($attribute, $value)
    {
        // Check if the password meets the criteria
        return preg_match('/[A-Z]/', $value) && // At least one uppercase letter
               preg_match('/[a-z]/', $value) && // At least one lowercase letter
               preg_match('/[0-9]/', $value) && // At least one number
               preg_match('/[\W_]/', $value);  // At least one special character
    }
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!$this->passes($attribute, $value)) {
            $fail($this->message());
        }
    }

    public function message()
    {
        return 'The :attribute must include at least one uppercase letter, one lowercase letter, one number, and one special character.';
    }
}

PasswordValidationRules :

Now simply call the Rule class on your Request file or trait as show below

<?php

namespace App\Actions\Fortify;

use Illuminate\Validation\Rules\Password;
use App\Rules\StrongPassword;

trait PasswordValidationRules
{
    /**
     * Get the validation rules used to validate passwords.
     *
     * @return array<int, \Illuminate\Contracts\Validation\Rule|array<mixed>|string>
     */
    protected function passwordRules(): array
    {
        return ['required', 'string', Password::default(), 'confirmed',new StrongPassword];
    }
}

Output :

How to Validate Weak and Strong Passwords in Laravel


Thank you for reading this article 😊

For any query do not hesitate to comment 💬



Previous Post Next Post

Contact Form