Joi - validate object keys and values?

joi
1977 picture 1977 · Mar 15, 2017 · Viewed 7.8k times · Source

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"
  }

Answer

blade picture blade · Sep 7, 2017

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,
    }
}