Tuesday, December 11, 2018

Laravel Create Custom Validator

As we all know that Laravel comes with in built set of custom validators like required, unique etc using which we can do form or request validations on server side. In this blog I am going to explain how to create custom validator.

Custom validator is required when you have some special logic validations. For example a field should be minimum of 12 characters, it should start with special prefix etc.

To do this Laravel provides way to create custom field validator. You have to extend Validator in boot method of AppServiceProvider. Here is the complete code.

use Validator;

public function boot()
        Validator::extend('VALIDATOR_NAME', function($attribute, $value, $parameters, $validator) {
               //validation logic
               //should return true or false

       Validator::replacer('greater_than_field', function($message, $attribute, $rule, $parameters) {
  return $attribute."MESSAGE".$parameters[0];

As you can see in above code, first we define validator with Validator::extend and then using Validator::replacer we can define the message to be displayed.

This way you can create your own validators and then use it with Validator class.

$this->validate($request, [

No comments:

Post a Comment