8
votes

how could I use Joi to validate a substitutions field has zero or more key /value pairs ? and that each key is a string and that each value is a string, number or bool ?

"substitutions": {
    "somekey": "someval",
    "somekey": "someval"
  }
2

2 Answers

16
votes

You can use Joi.object().pattern():

{
    substitutions: Joi.object().pattern(/.*/, [Joi.string(), Joi.number(), Joi.boolean()])
}

This would work with payloads like:

{
    substitutions: {
        blah   : 'string',
        test123: 123,
        example: true,
    }
}
-1
votes

To allow a key to match multiple types, you need to use Joi.alternatives().

Your schema would look like:

const schema = {
    substitutions: Joi.object().keys({
        somekey: Joi.alternatives().try(Joi.string(), Joi.number(), Joi.boolean())
    })
};