Search code examples
phplaravellaravel-validation

Laravel Validator Facade - Validate size based on another field value


I have a form where the user must define the number of items to save and when you submit the form and parse it to JSON it looks like this:

{
 "numItems": 3,
 "items": [
     "1" : {"A": "Foo", "B:"bar"},
     "2" : {"A": "Foo", "B:"bar"},
     "3" : {"A": "Foo", "B:"bar"},
 ],
}

And I want to validate that the number of items inside items matches with the value of numItems.

I've tried with:

$aValidations = [
    "numItems" => "required|int|max:10",
    "items" => "required|array|size:numItems",
]

But even if the number of item matches the numItems value I get this:

{
    "message": "The given data was invalid.",
    "errors": {
        "items": ["The items must contain numItems items."]
    }
}

How can I achieve this?


Solution

  • One way would be to write a custom validator (you can put this in your AppServiceProvider@boot method). Something like (not tested/pseudocode):

    Validator::extend('coolValidatorName', function ($attribute, $value, $parameters, $validator) {
            $data = $validator->getData();
            return $data[$parameters[0]] == count($value)
        });
    

    https://laravel.com/docs/5.5/validation#custom-validation-rules