Elymentree
Elymentree

Reputation: 853

Validating the key in the data in Lumen

I am validating a request that looks like this:

 {
  "data": [
    {
      "id": 1,
      "name": "Foo",     
      "values":{
        "val1":"This",
        "99":"That"
      }
    }
  ]
}

Here is my custom messages:

$messages = [
     'data.id'=>'is required',
     'data.name'=>'is required',
     'data.values'=>'must be array',
     'data.values.*'=>'must be numeric'
];

My validation rule is this:

$this->validate(
            $request,
            [
                'data'=>'required|array',
                'data.*.id'=>'required|numeric',
                'data.*.name'=>'required',
                'data.*.values'=>'array',
                'data.*.values.*'=>'numeric'
             ],
            $messages
        );

The rule validates the values in the "values" array. I want to validate the key in the "values" array [val1, 99] instead.

Upvotes: 0

Views: 478

Answers (1)

Jeff
Jeff

Reputation: 25221

Write a custom validation rule for data.*.values:

'data.*.values' => function($attribute, $value, $fail) {
    //$value contains your array of $key => $value pairs for you to loop through
    if( /* doesn't pass your rules */){
        return $fail('custom validation failed');
    }
},

Upvotes: 1

Related Questions