Custom Validation Rules In Laravel 5.5
Recently, Adam Wathan showed me a fresh approach to writing custom validation rules that he was implementing in his own projects. So, Adam and I decided to pair program the feature into Laravel one morning, and I’m really happy with the results.
Defining The Rule
I’ll use some code I recently wrote in an actual application to demonstrate the feature. In my application, I need to verify that a given GitHub repository and branch actually exists. Of course, the only way to do this is by making an API call to GitHub. This validation requirement is a great candidate for wrapping inside a custom validation rule. To get started, we simply define a class with two methods: passes
and message
. I chose to place my class in the App\Rules
namespace:
Let’s digest this code. The passes
method will receive the $attribute
and $value
arguments from the Laravel Validator. The $attribute
is the name of the field under validation, while the $value
is the value of the field. This method only needs to return true
or false
, depending on whether the given value is valid or not.
In my example, the Source
object is an Eloquent model that represents a source control provider such as GitHub.
The message
method should return the appropriate error message to be used when validation fails. Of course, within this method you may retrieve a string from your translation files.
Using The Rule
Once we have defined our custom validation rule, we can use it during a request. To assign the rule to an attribute, we simply instantiate it within our array of rules. In this example, I’ll use the validate
method, which is available directly from the Request object in Laravel 5.5:
Of course, you could also use your custom rule from within a Form Request or any other location where you perform validation.
This new feature provides a quick, easy way to define custom validation rules, and I’ve already made heavy use of this feature in my own code. I hope you will too. Enjoy!