Custom validator in Laravel 5

Try the following:

  1. Make a bind class where you can implement each rule you want extending Validator class.
  2. Make a service provider that extends ServiceProvider.
  3. Add your custom validator provider at config/app.php file.

You can create the bind at Services folder like this:

namespace MyApp\Services;

class Validator extends \Illuminate\Validation\Validator{

    public function validateFoo($attribute, $value, $parameters){  
        return $value == "foo"
    }
}

Then, use a service provider to extends the core:

namespace MyApp\Providers;

use MyApp\Services\Validator;
use Illuminate\Support\ServiceProvider;

class ValidatorServiceProvider extends ServiceProvider{

    public function boot()
    {
        \Validator::resolver(function($translator, $data, $rules, $messages)
        {
            return new Validator($translator, $data, $rules, $messages);
        });
    }

    public function register()
    {
    }
}

Finally, import your service provider at config/app.php like so:

'providers' => [
    ...
    ...
    'MyApp\Providers\ValidatorServiceProvider';
]

Leave a Comment