Custom Validation Rules in Laravel 5.5

Custom Validation Rules in Laravel 5.5

Custom validation rules introduced in Laravel 5.5. Laravel custom validation makes it possible to add validation rules that are not defined in laravel.

In this article, we will try to determine if a phone number is valid or not using laravel custom validation rules.

Get started by creating the validation rule using the following artisan command:

The above command should create a file called PhoneNumberValidationRule.php in the app/Rules folder.

By default, the artisan command will generate the following code snippet for you.

Note that, the class PhoneNumberValidationRule has two methods: passes and message.

However, the passes method receives the $attribute and $value arguments from the Laravel Validator. In short, $attribute is the field under validation, while $value as the variable suggests is the value of the field. The passes method return true or false to determine the validity of the given value.

To validate our phone number, update the passes method with the code below:

In addition, the message return the error message define when validation fails. Of course, update the message method with the code below:

Using the Validation Rule

Finally, use the custom rule in the Controller during request. On the other hand, simply instantiate the custom validation class in the array rules in order to assign the rule to an attribute. For instance, use the validation method from the Request object in Laravel 5.5

Of course, if you prefer using as a Closure, the function looks like the following:

Further, if you want the rule empty field in the request, then, use the ImplicitRule contract. Use the Closure to experiment with the custom rule and then change to an object if the rule proves successful.

In conclusion, this new feature in Laravel 5.5, is an easy way to define custom validation rule. Enjoy using this feature in your code.

Clemence Ayekple

Let's grab a cup of coffee and talk about programming

Add comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most discussed

%d bloggers like this: