How to Create a Custom Validation Rule in Laravel

Laravel’s built-in Validation feature comes with a bunch of validation rules like required, email, array etc. But, in some situations you may want to create your own custom rule. For example, in this tutorial we are going to create a validation rule which will check if the email address provided by user belongs to Gmail or not.

To create a custom validation rule follow the steps given below;

Step 1 : Define the rule:

In the first step we are going to define a new rule by extending the Laravel Validator class. We are going to put our new validation rule inside app\Providers\AppServiceProvider.php file that comes bundled with Laravel. You can also use your own custom service provider to put this code.

Validator::extend('gmail', function($attribute, $value)
{
     $domain = explode('@', $value);
     return (isset($domain[1]) && $domain == 'gmail.com') ? true : false;
});

In the above code, gmail is the name of the of our newly created validation rule. The method will return return TRUE if the validation is passed else it will return FALSE. 

Step 2 : Create Custom Validation Message

To set a custom validation message for our rule add the following code to main validation array.

'gmail' =>  'The :attribute must be a valid Gmail Address',

To use the new rule add it to rules array.

$rules = [
        'email' => 'required|gmail',
];

And that’s it. I case you have any queries feel free to comment.

0 Comments

Leave a Comment.