3

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?

5
  • 2
    Does this question help: stackoverflow.com/questions/42258185/… Commented Oct 6, 2021 at 8:14
  • What do you mean when you say "..I think for that I can only pass a string"? Does that mean your array does not contain strings? Commented Oct 6, 2021 at 8:18
  • I think your link did help 'values.*' => 'string|in:name,title,description' seems to work Commented Oct 6, 2021 at 8:20
  • This question has incorrectly been marked as a duplicate as I am validating an array, not a string as in the "duplicate" question. Commented Jun 27, 2024 at 8:07
  • As mentioned in the accepted answer of the linked question, your validation rule 'values.*' => 'string|in:name,title,description' really means "for each element of the array 'values' each string element must match one of the specified values (name, title, or description)." Although you are passing an array, you are validating strings in the array. Commented Jun 27, 2024 at 10:23

2 Answers 2

3

Validate each string in the array:

'values.*' => 'string|in:name,title,description'
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.