Mauro Baptista

I'm a software developer! I'm comfortable with PHP and Javascript. Currently developing this blog and a limo reservation app using Laravel and TDD!

Always learning something new!

January 19, 2017 at 00:00 / By Mauro Baptista Laravel PHP

How to add multiple custom validations

I had to create a custom validation to a project, so I've included on the AppProvider something like:


Validator::resolver(function ($translator, $data, $rules, $messages, $validator) {
    return new MyCustomValidator($translator, $data, $rules, $messages, $validator);
});

Ok. It works well! But then I had to include another custom validation, as a simple answer I've just added one more Validator::resolver on the provider, and ok!?! Hummm.. Houston we have a problem! Just the second one was running, the first one was ignored.

Googling it, I've come with this solution:

On the folder App, create a folder Validator, and inside it we will keep all files that have validation logic.

Example:

A file named OddValidator.php, that handles the validation to check if a number is odd:


namespace App\Validators;

class OddValidator
{
    public function validateOdd($attribute, $value, $parameters, $validator)
    {
        return $value % 2 === 1;
    }
}

Another file named EvenValidator.php, that handles the validation to check if a number is even:


namespace App\Validators;

class EvenValidator
{
    public function validateEven($attribute, $value, $parameters, $validator)
    {
        return $value % 2 === 0;
    }
}

These are my two custom validations. Now we must have a file to get this two files, it will be our validation handler.

File: CustomValidationHandler.php


namespace App\Validators;

use App\Validators\EvenValidator;
use App\Validators\OddValidator;
use Illuminate\Validation\Validator;

class CustomValidationHandler extends Validator
{
    public function validateEven($attribute, $value, $parameters, $validator)
    {
        return (new EvenValidator)->validateEven($attribute, $value, $parameters, $validator);
    }

    public function validateOdd($attribute, $value, $parameters, $validator)
    {
        return (new OddValidator)->validateOdd($attribute, $value, $parameters, $validator);
    }
}

On this file we will just call our two custom validations.

Note: Could you use these function to include you validation logic? Yes, of course, but on this example all validation is simple, and I believe that using separated files keeps the code more organized.

Now on our AppServiceProvider, add the Validator::resolve on the boot method:


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

Note: Do not forget to import the custom validation handler class use App\Validators\CustomValidationHandler; on top of your file.

Now, you can add the error message on the translation fields (resources/lang/en/validation.php)


'even' => 'The :attribute must be an even number',
'odd'  => 'The :attribute must be an odd number.',

Now you can add a rule at your validations, like:


$this->validate($request, [
   'my-field' => 'even',
]);

Whoops, looks like something went wrong.

1/1 ErrorException in Filesystem.php line 111: file_put_contents(): Only 0 of 299 bytes written, possibly out of free disk space

  1. in Filesystem.php line 111
  2. at HandleExceptions->handleError('2', 'file_put_contents(): Only 0 of 299 bytes written, possibly out of free disk space', '/opt/bitnami/apps/carnou.com/blog/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php', '111', array('path' => '/opt/bitnami/apps/carnou.com/blog/storage/framework/sessions/Q8vCsXWYUwgZOgQSCIXyikS4t5yKuzir1broVXcR', 'contents' => 'a:4:{s:6:"_token";s:40:"pRKu8PONvOqT5XsEbCoTuIfYs59DyFLvJUCZ3bsR";s:9:"_previous";a:1:{s:3:"url";s:61:"http://carnou.com/post/how-to-add-multiple-custom-validations";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1519159949;s:1:"c";i:1519159949;s:1:"l";s:1:"0";}s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}', 'lock' => true))
  3. at file_put_contents('/opt/bitnami/apps/carnou.com/blog/storage/framework/sessions/Q8vCsXWYUwgZOgQSCIXyikS4t5yKuzir1broVXcR', 'a:4:{s:6:"_token";s:40:"pRKu8PONvOqT5XsEbCoTuIfYs59DyFLvJUCZ3bsR";s:9:"_previous";a:1:{s:3:"url";s:61:"http://carnou.com/post/how-to-add-multiple-custom-validations";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1519159949;s:1:"c";i:1519159949;s:1:"l";s:1:"0";}s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}', '2') in Filesystem.php line 111
  4. at Filesystem->put('/opt/bitnami/apps/carnou.com/blog/storage/framework/sessions/Q8vCsXWYUwgZOgQSCIXyikS4t5yKuzir1broVXcR', 'a:4:{s:6:"_token";s:40:"pRKu8PONvOqT5XsEbCoTuIfYs59DyFLvJUCZ3bsR";s:9:"_previous";a:1:{s:3:"url";s:61:"http://carnou.com/post/how-to-add-multiple-custom-validations";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1519159949;s:1:"c";i:1519159949;s:1:"l";s:1:"0";}s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}', true) in FileSessionHandler.php line 83
  5. at FileSessionHandler->write('Q8vCsXWYUwgZOgQSCIXyikS4t5yKuzir1broVXcR', 'a:4:{s:6:"_token";s:40:"pRKu8PONvOqT5XsEbCoTuIfYs59DyFLvJUCZ3bsR";s:9:"_previous";a:1:{s:3:"url";s:61:"http://carnou.com/post/how-to-add-multiple-custom-validations";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1519159949;s:1:"c";i:1519159949;s:1:"l";s:1:"0";}s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}') in Store.php line 263
  6. at Store->save() in StartSession.php line 88
  7. at StartSession->terminate(object(Request), object(Response)) in Kernel.php line 177
  8. at Kernel->terminate(object(Request), object(Response)) in index.php line 56