Strong Password Validation Rule in Laravel Custom or Regex

Laravel Strong Password Validation Example; In this tutorial we will show you how to create and set strong password validation rule in Laravel apps. More then times we need to make a strong password validation for authentication eg in registeration and reset password. So we need to add custom or regex for creating a valid and strong password in laravel application.

Sometimes we need to add password validation rule in the validator like this:

Laravel strong Password Validation rule:

  • English uppercase characters (A – Z)
  • English lowercase characters (a – z)
  • Base 10 digits (0 – 9)
  • Non-alphanumeric (For example: !, $, #, or %)
  • Unicode characters

Laravel Custom Strong Password Validation

A custom laravel validation rule will allow developers to provide a custom message with each use case for a better UX experience. So the below we have added the strong laravel validation for password here.

Make a Rule

First create a new rule called IsValidPassword just running the following command:

php artisan make:rule IsValidPassword

Now open app/Rules/IsValidPassword.php file and paste bellow code on it:

<?php

namespace App\Rules;

use Illuminate\Support\Str;
use Illuminate\Contracts\Validation\Rule;

class IsValidPassword implements Rule
{
    /**
     * Determine if the Length Validation Rule passes.
     *
     * @var boolean
     */
    public $lengthPasses = true;

    /**
     * Determine if the Uppercase Validation Rule passes.
     *
     * @var boolean
     */
    public $uppercasePasses = true;

    /**
     * Determine if the Numeric Validation Rule passes.
     *
     * @var boolean
     */
    public $numericPasses = true;

    /**
     * Determine if the Special Character Validation Rule passes.
     *
     * @var boolean
     */
    public $specialCharacterPasses = true;

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->lengthPasses = (Str::length($value) >= 8);
        $this->uppercasePasses = (Str::lower($value) !== $value);
        $this->numericPasses = ((bool)preg_match('/[0-9]/', $value));
        $this->specialCharacterPasses = ((bool)preg_match('/[^A-Za-z0-9]/', $value));

        return ($this->lengthPasses && $this->uppercasePasses && $this->numericPasses && $this->specialCharacterPasses);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        switch (true) {
            case !$this->uppercasePasses
                && $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 8 characters and contain at least 1 uppercase character.';

            case !$this->numericPasses
                && $this->uppercasePasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 8 characters and contain at least 1 number.';

            case !$this->specialCharacterPasses
                && $this->uppercasePasses
                && $this->numericPasses:
                return 'The :attribute must be at least 8 characters and contain at least 1 special character.';

            case !$this->uppercasePasses
                && !$this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 8 characters and contain at least 1 uppercase character and 1 number.';

            case !$this->uppercasePasses
                && !$this->specialCharacterPasses
                && $this->numericPasses:
                return 'The :attribute must be at least 8 characters and contain at least 1 uppercase character and 1 special character.';

            case !$this->uppercasePasses
                && !$this->numericPasses
                && !$this->specialCharacterPasses:
                return 'The :attribute must be at least 8 characters and contain at least 1 uppercase character, 1 number, and 1 special character.';

            default:
                return 'The :attribute must be at least 8 characters.';
        }
    }
}

Apply Rule in Controller

After that we need to use the isValidPassword rule in our controller on validator function something like this.

use App\Rules\IsValidPassword;

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'confirmed', new isValidPassword()],
    ]);
}

Laravel Strong Password Validation with Regex

We can use regular expression (Regex) for making strong password validation rule as well in laravel app.

The password contains characters these following categories:

  • English uppercase characters (A – Z)
  • English lowercase characters (a – z)
  • Base 10 digits (0 – 9)
  • Non-alphanumeric (For example: !, $, #, or %)
  • Unicode characters

Lets add the following regular expression in your validator function something like below.

Your regular expression would look like this:

^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$

So your final Laravel code should be like this:

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/|', 'confirmed'],
    ]);
}

Regex for Strong Password Validation in Laravel

regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/'

The above regex means the following

  • Should have At least one Uppercase letter.
  • At least one Lower case letter.
  • Also,At least one numeric value.
  • And, At least one special character.
  • Must be more than 6 characters long.

So, Laravel strong password validation example tutorial we have implemented how to create custom strong password validation in laravel application.

Leave a Comment