Site icon Web Niraj

Laravel 5.x: Custom Password Reset Validation

Having a strong password policy for your application is a important security requirement for any application. Unfortunately, the default password requirements in Laravel 5 isn’t up to scratch. However, you can easily update the password requirements of your application by adding a regex validation rule. This tutorial shows you how you can apply this to the PasswordController, which handles password resets.

The Regex

The important part of any password policy is to determine if the password has the minimum character requirements. In a recent application I developed, the password policy required:

All of these requirements can be captured in a regular expression test:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z0-9]).+$/

Since Laravel’s regex validation rule checks if a regex is true, the above regex is prefixed with ^, which returns false if any of the above conditions are false.

Updating the PasswordController

Now that we have our regex in place, we can update the app/Http/Controllers/Auth/PasswordController.php file with our new validation rules. This is done by adding two new functions to the file: getResetValidationRules() and getResetValidationMessages(). Both these functions are self-explanatory: the first adds the validation rules to apply, and the second adds the custom validation messages. The end result is:

See the gist on github.

The original password validation rule has been changed from required|confirmed|min:6 to required|confirmed|min:8|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z0-9]).+$/. In addition to adding the regex validation rule, we’ve also changed the minimum password length to 8 characters (using min).

AuthController Updates

The same password policy can be applied to app/Http/Controllers/Auth/AuthController.php. This can be achieved by updating the validator(array $data) function. Since this function applies both the rules and messages, this is the only function that needs to be edited. This is what the result would look like:

See the gist on github.


If this tutorial has helped you solve a problem please tell me able it in the comments section below. Also, comment and let me know if you need help or have a suggestion.

Exit mobile version