Creating custom validation rule in Laravel

You must be aware about the predefined validation rules provided by Laravel, if not then please first have a look in this.

But these rules do not work for all requirement, sometimes you need to create your own validation rule.

Here is how you generally writes the validations on a request in a controller

Now think about a situation where you need to create a custom validation for example

A username should not contain more than 3 numbers

For this we have to create a new rule, name it num_check.

Something like-

We can also make number check variable like

num_check:3 will check not to have more than 3 numbers and where num_check:5 will check not have more than 5 numbers, similarly num_check:x will not allow to have more than x number in a string.

We can also pass multiple parameters like  num_check:x,y,z

Now we have to extend our validator. Modify file app/Providers/AppServiceProvider.php

After adding this code num_check:x  will work similar as other rules in Laravel.

Read out creating API responder in Laravel.

Please follow and like us: