rleger's avatar

Custom laravel 5 validation rules

Hi everyone,

I'm looking to create a custom validation rules with larvel 5 to use within my FormRequest. Specifically a require_if_not rule.

to do something like :

public function rules () {
return [
"aField" => "require_if_not:someOtherField,hasSomeValue",
...

I've looked at a few options and none does the job how I want it to.

This thread comes close but it actually performs some more checks after the validation passes and I'd like to implement a rule rather than hardcoding checks afterwards. https://laracasts.com/discuss/channels/general-discussion/custom-validation-function-in-laravel-5

Of course larvel 4 validation extension would do the job exactly as I would like, but I can't seem to translate it for L5. (http://culttt.com/2014/01/20/extending-laravel-4-validator/)

Any thoughts ?

Thanks !

0 likes
5 replies
rleger's avatar

Thanks!!! I missed it.

Still I can't get any one working, extending from the FormRequest Constructor or creating a separate file that will be loaded through a service provider.. am I missing something or did it change since that commit..

Starting to pull my hair on this.

Pretty straight forward though ...


use Illuminate\Validation\Factory; class AnswersFormRequest extends Request { public function __construct(Factory $factory) { $factory->extend('test', function ($attribute, $value, $parameters) { return false; }, 'Bad number format' ); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ "ville" => "test",

The validation passes !!

rleger's avatar

it works when using the extendImplicit method although I don't really understand the difference

  $factory->extendImplicit('test', function ($attribute, $value, $parameters)
            {
                // return logic test
            },
            'Bad number format'
        );
bestmomo's avatar

Implicits extensions are if you dont need value (that is in array with rule name) like "required", it's your case. So it cant work with "extend".

rleger's avatar

Ok. If I get it right extendImplicit will run even if no inputs are provided for the field when extend will only run if one is.

Thanks.

Please or to participate in this conversation.