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.

Can I do this without using a custom rule?

reans
  • 352
  • 1
  • 5
  • 16
  • 2
    Does this question help: https://stackoverflow.com/questions/42258185/how-to-validate-array-in-laravel – Tony Oct 06 '21 at 08: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? – Tony Oct 06 '21 at 08:18
  • I think your link did help `'values.*' => 'string|in:name,title,description'` seems to work – reans Oct 06 '21 at 08:20
  • glad to hear it helped. Perhaps add your own answer and accept it so your question does not show up as unanswered :) – Tony Oct 06 '21 at 08:27

2 Answers2

3

Validate each string in the array:

'values.*' => 'string|in:name,title,description'
reans
  • 352
  • 1
  • 5
  • 16
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

ya-cha
  • 602
  • 2
  • 6
  • 14