Validating Password Strength

Last updated: Wednesday 2nd October, 2024 02:28 AM IST
  1. Home
  2. Articles
  3. Validating Password Strength
Validating Password Strength

Custom Validation Rules in Laravel: Validating Password Strength

In today's digital landscape, strong password policies are more important than ever. With increasing concerns about data breaches and unauthorized access, ensuring that users create strong, secure passwords is a critical aspect of application development. While Laravel provides some built-in validation rules, they often fall short of enforcing comprehensive password strength requirements. In this post, we will create a custom validation rule in Laravel to validate password strength based on specific criteria.

Why Validate Password Strength?

Enhancing Security

Weak passwords are one of the most common vulnerabilities in web applications. By enforcing a strong password policy, you can significantly reduce the likelihood of unauthorized access and data breaches. Strong passwords are harder for attackers to guess or crack, thereby providing an essential layer of security for user accounts.

User Awareness

When users are required to create strong passwords, they become more aware of the importance of security. Educating users about password complexity not only helps them in your application but also encourages good security practices across their online activities.

Regulatory Compliance

Certain industries have strict regulations regarding password policies. For example, applications handling sensitive data, such as healthcare or financial information, may be required to adhere to specific security standards. Implementing a strong password validation rule can help ensure compliance with these regulations.

Creating a Custom Password Strength Validation Rule

Step 1: Generate the Custom Rule Class

To get started, we need to create a new validation rule for checking password strength. Laravel provides a convenient Artisan command to generate a custom rule class. Run the following command in your terminal:

php artisan make:rule StrongPassword

This command will create a new file in the app/Rules directory named StrongPassword.php.

Step 2: Implement the Validation Logic

Next, open the newly created StrongPassword.php file. Here, we will implement the logic to validate the strength of a password. A strong password should meet several criteria:

  • At least one uppercase letter
  • At least one lowercase letter
  • At least one number
  • At least one special character (e.g., @, #, $, etc.)
  • A minimum length of 8 characters

Here’s how you can implement this logic:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class StrongPassword implements Rule
{
    public function passes($attribute, $value)
    {
        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 digit
               preg_match('/[\W]/', $value) &&      // At least one special character
               strlen($value) >= 8;                  // Minimum length
    }

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

Step 3: Using Your Custom Validation Rule

Now that we’ve created the custom rule, let’s see how to implement it in your application.

Applying in a Form Request

If you’re using a Form Request in Laravel, you can apply the custom validation rule like this:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Rules\StrongPassword;

class RegisterUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'password' => ['required', 'string', new StrongPassword()],
            // other validation rules...
        ];
    }
}

Applying Directly in a Controller

Alternatively, if you prefer to validate directly within your controller, you can do so as follows:

use App\Rules\StrongPassword;

public function register(Request $request)
{
    $request->validate([
        'password' => ['required', 'string', new StrongPassword()],
        // other validation rules...
    ]);

    // Proceed with user registration...
}

Step 4: Testing Your Custom Validation Rule

It’s crucial to test your custom validation rule to ensure it behaves as expected. Laravel provides a robust testing framework that allows you to create tests easily. Create a test file for your custom rule using Artisan:

php artisan make:test StrongPasswordTest

In this test file, you can implement tests to check both valid and invalid password scenarios:

namespace Tests\Unit;

use Tests\TestCase;
use App\Rules\StrongPassword;

class StrongPasswordTest extends TestCase
{
    public function test_password_is_strong()
    {
        $rule = new StrongPassword();

        // Valid passwords
        $this->assertTrue($rule->passes('password', 'StrongPass1!'));
        $this->assertTrue($rule->passes('password', 'Another@123'));

        // Invalid passwords
        $this->assertFalse($rule->passes('password', 'weakpassword'));
        $this->assertFalse($rule->passes('password', '12345678'));
        $this->assertFalse($rule->passes('password', 'NoSpecialChar1'));
    }

    public function test_custom_message()
    {
        $rule = new StrongPassword();

        $this->assertEquals('The :attribute must be at least 8 characters long, and include at least one uppercase letter, one lowercase letter, one number, and one special character.', $rule->message());
    }
}

Run your tests with the following command to ensure everything works as expected:

php artisan test

Best Practices for Custom Validation Rules

Clear Messaging:

Ensure that your validation error messages are clear and instructive. Users should know exactly what is wrong with their input.

Password Policies:

Consider allowing configurable password policies. This can help accommodate different application requirements without altering the core validation logic.

User Education:

Provide users with guidance on creating strong passwords. You can include tooltips or help text next to the password field to reinforce good practices.

Feedback Mechanism:

Implement real-time feedback in your user interface, informing users whether their password meets the strength requirements as they type.


Conclusion

Creating custom validation rules in Laravel, such as for validating password strength, allows you to enforce specific business requirements effectively. By ensuring that passwords meet certain criteria, you not only enhance the security of your application but also promote better user practices.

Start implementing custom validation rules in your Laravel applications today and provide your users with the security they need!

Mehul Bawadia

Author:

Mehul Bawadia is a Full Stack Developer in Laravel and VueJs, based in Mumbai, India. He has an overall experience of 8 years in the website development field. When he is not working, you will find him learning new stuff that is not related to work.

Process Followed

1. Discover

In this process, I learn more about the requirements from you and/or from the client, and come up with varios permutations and combinations to meet the requirements.

2. Design

Once I learn properly, I do the design of the requirements that you gave keeping things aesthetically pleasing & useable for your audience.

3. Develop

Once you and/or the client is happy with the design(s), I start with the development process of the said requirements.

4. Deploy

After development, I will send the developed task to the client for reviewing. Once confirmed, will be deployed to the live server.

Tech Stack

HTML 5

HTML 5

CSS 3

CSS 3

TailwindCSS

TailwindCSS

JavaScript

JavaScript

PHP

PHP

MySQL

MySQL

Laravel

Laravel

VueJs

VueJs

Spare time Projects

Few of the simple projects simply to learn.

View Projects
Copyright © 2024, BMehul. All Rights Reserved.
Built with A heart icon by Mehul Bawadia.
An arrow that takes you to the top of the page when clicked