reans
reans

Reputation: 430

Laravel validate array values contained in list

EDIT: This question is clearly not a duplicate of the linked question. The other question is about validating strings. This question is about validating arrays. Not only did the person who flagged as a duplicate not read the question, the site has been completely ineffectual in resolving this false duplication flag.

I am passing an array in a request to my api. Each value within the array must be within a pre-defined list.

If my list is: name,description,title

name, title //valid
different, title //invalid

I tried array|in:name,description,title but I think for that I can only pass a string as opposed to an array.

I understand I can use:

'values' => 'in:name',

However this is when I am passing a string in my json request body eg. { "values": "name"}. I am trying to pas an array eg. { "field": ["name", "description"]}

Can I do this without using a custom rule?

Upvotes: 3

Views: 2392

Answers (2)

reans
reans

Reputation: 430

Validate each string in the array:

'values.*' => 'string|in:name,title,description'

Upvotes: 3

ya-cha
ya-cha

Reputation: 622

Have a look at "Validating Nested Array Input"

If I understand you correctly your validation rules should be (untested)

[
   '*.name' => 'required|string',
   '*.description' => 'required|string',
]

Maybe you also want to exclude unvalidated Keys

Upvotes: 0

Related Questions