0

How can I validate an object with unknown keys with Joi? Here is an example of my data

{
'5520': {
    name: 'string',
    order: 0,
},
'8123': {
    name: 'string',
    order: 5,
},
'8219': {
    name: 'string',
    order: 1,
},
'10113': {
    name: 'string',
    order: 2,
},
'14538': {
    name: 'string',
    order: 6,
},
'15277': {
    name: 'string',
    order: 4,
},
'16723': {
    name: 'string',
    order: 3,
}

I would like to validate each one of those unknown keys to make sure they all contain name, order and a few other properties, they all must have the same properties.

I read their documentation, just can't figure out how to deal with those unknown keys.

Guilhermo
  • 5
  • 3
  • Does this answer your question? [Joi object validation: How to validate values with unknown key names?](https://stackoverflow.com/questions/41741612/joi-object-validation-how-to-validate-values-with-unknown-key-names) – Ankh Aug 05 '21 at 10:05

1 Answers1

1

You can use object.pattern:

Joi.object().pattern(
    /\d/, 
    Joi.object().keys({
      name: Joi.string().valid('string'),
      order: Joi.number().integer(),
    })
)

This means that your keys must be numbers, and their value must be the object defined with name and order, which means, any of your example data will pass.

soltex
  • 2,993
  • 1
  • 18
  • 29