Site icon Web Niraj

Laravel 5.x: Custom Validation Rules

Sometimes, the default validation rules included in Laravel 5.x isn’t enough for bespoke applications. For example, what if I want a validation rule that checks if a field matches the current user’s password in the database? There isn’t a rule for that, but luckily its fairly easy to add custom rules. This tutorial shows you how.

My requirement was a custom validation rule that checks if the entered password for the user matches the one stored in the database. This is so I can validate the user’s request to update their password. The form would use three fields: current_password, password, password_confirmation, and it’s the current_password that I want to validate.

Including the Required Dependencies

In order to create a custom validation rule, you need to make sure the relevant classes are included in your code. In my example, we need the use statement to include the following classes:

Creating the Custom Password Validator

To create the custom validation rule, we use the Validator::extend function to create a new rule called password. The function accepts a name and Closure to create the rule. Lines 10-13 below show how I created the rule for checking the password.

See the gist on github.

I also created the $messages array to include a custom error message should validation fail, and passed this to the Validator::make function (as the third parameter). Here is a line-by-line breakdown:

Another Example

To give you a better idea of how it all works, here is another example. This time, I’ve created a rule called startswith, which validates that a field starts with the required prefix. In this example, the validation rule also accepts parameters: the prefix. So, if I want to validate that UK Mobile numbers start with ’07’, I would create a custom validator as following:

See the gist on github.

Putting it All Together

One-off validation rules work best in Controllers, for example, the below code shows how the validation rule comes together with other code. If you want your validation rules to be available across multiple files / controllers, you can also register them within a service provider.

See the gist on github.

Exit mobile version