Create a custom validator in 4 steps

Laravel comes with a great validation system, but sometimes it’s not enough and you need to write your own custom validator.

After some googling, coding, and a big headache, here’s how to do it.

1. The Validator object

There isn’t a default place for validators, so, just like controllers, models, etc, I think it was a good idea to create an app\Validators folder.

Inside it, create a new file testValidator.php with a validate function:

<?php

namespace App\Validators;

use Validator;

class TestValidator extends Validator {

  public function validate($attribute, $value, $parameters, $validator) {
    if ($value == 'Hello World!') {
      return true; // Return true if validation ok
    }
    return false; 
  }
}

You must extend Validator in order to make it work. The validate function takes four parameters:

  • $attribute: the name of the attribute under validation
  • $value: the value taken from the input field
  • $parameters: optional parameters passed in (see chapter 3)
  • $validator: a validator instance

If the value is ok, we must return true, otherwise, return false;

2. The service provider

Using artisan, create a new service provider “ValidatorsServiceProvider“:

php artisan make:provider ValidatorsServiceProvider

Open it and make sure it looks like this:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Validator;

class ValidatorsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
      Validator::extend('test', 'App\Validators\TestValidator@validate');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Validator::extend is where we define the validator, in this case we are defining a “test” validator, wich will execute App\Validators\TestValidator@validate function.

3. Test it

Now you can use it in your controller:

public function store(Request $request)
{
    $this->validate($request, [
     'someVar' => 'test:param1,param2',
    ]);
}

param1, param2, etc are passed to the validate function as $parameters.

4. Custom error messages

To show a custom error message for your validator, just add it to resources/lang/XX/validation.php 

'test'             => 'Test validator error for :attribute',

And that’s all! Have fun!