How to Create a Custom Validation Rule in Laravel

Step 1 : Define the rule:

 

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.


Posted

in

by

Tags:

Comments

Leave a Reply