Search code examples
phpvalidationlaravel-5.1custom-validators

Laravel 5.1: custom validation class


I made this custom validation class, CustomValidator.php:

<?php

namespace App;

use Illuminate\Validation\Validator;

class CustomValidator extends Validator{

    public function validateRequiredWithOneOf($attribute, $value, $parameters)
    {
        $data = $this->getData();
        foreach ($parameters as $p) {
            if ( array_get($data,$p) != null) {return true;}
        }

        return false;
    }

    public function replaceRequiredWithOneOf($message, $attribute, $rule, $parameters)
    {
        return $this->replaceRequiredWith($message, $attribute, $rule, $parameters);
    }
}

which I call in my CustomRequest.php

'input_field' => 'required_with_one_of:first,second,third',

If the attribute input_field is selected, then at least one of the parameter fields (first,second,third) must be selected also.

If I define custom validation inside of boot() method of AppServiceProvider.php it all works but not if I create this CustomValidator class and delete the code from AppServiceProvider.php.

This doesn't surprise me since I'm calling Validator and not CustomValidator in my CustomRequest class.

My CustomRequest class extends Request classs which extends FormRequest class in which Validator is mentioned in many places. I really don't know where to start here. If required I can c/p the FormRequest class here.

Can anybody help me work this one out?


Solution

  • After creating CustomValidator just call resolver method in the boot() method:

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

    Also, calling it inside of CustomRequest does not make differece. Should works without problems.