Validating unnamed arrays

Hi!

I’m trying to validate an array with objects, and while I know the basics for doing this, my case seems to be a little different from what I can find in the docs so if anyone could give me some pointers I’d be very thankful.

So given the following data structure:

{
  user_array: [
    {
      id: 1
    },
    {
      id: 2
    }
  ]
}

The following validation rule works as expected:

'user_array.*.id': 'required'

But… my frontend colleague for whom I’m building an API requires me to to accept the following data structure:

[
  {
    id: 1
  },
  {
    id: 2
  }
]

So it’s almost the same but I don’t have a name for the array that I can reference in the validator.

The following works:

'0.id': 'required',
'1.id': 'required'

But the following does not:

'*.id': 'required'

Obviously the first method isn’t in any way desirable as I never know how many objects the array I receive will contain, but sadly the index wildcard won’t work for me. Anyone else who’s run into this problem?

Thanks in advance for any help!

1 Like

Not the answer you are looking for.
I would go with the structure you provided at the beginning. You never know when additional params creep in to the back and forth conversations b/w client & server :slight_smile:

Thanks for your reply! I guess I’ll go with my original data structure then. I’ll explain to the frontend team that it’s less work for them to put the array in an object so they can name it, instead of me rewriting an entire validation library :man_shrugging:

I would suggest simply push them that it is bad design (even if you keep the validation library aside).

As @prashanth1k said, there is no scope to introduce new key/value pair + there is no way to know what exactly this array stands for.

As an escape hatch, you can yourself put the array inside an object and then validate it.

const data = {
  someName: request.input('whatever-key')
}

const rules = {
  'someName.*.id': 'required'
}