10

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"
  }
1977
  • 2,580
  • 6
  • 26
  • 37
  • 1
    Possible duplicate of [Is there a way to validate dynamic key names?](http://stackoverflow.com/questions/43050870/is-there-a-way-to-validate-dynamic-key-names) – Ankh Mar 28 '17 at 07:56

2 Answers2

22

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,
    }
}
Aidin
  • 25,146
  • 8
  • 76
  • 67
blade
  • 12,057
  • 7
  • 37
  • 38
  • @Natan If this was useful to you, please [upvote](//stackoverflow.com/privileges/vote-up) this question for future readers. – lealceldeiro Aug 20 '18 at 17:30
  • Order of keys is not ensured because of js or json serialization ( I am not quiet sure what it is ), keys are usually at the same place but after some transformation position of them may be changed. This solution is not safe and may cauze critical production errors in your apps. – czlowiek488 May 31 '22 at 13:37
-2

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())
    })
};
Cuthbert
  • 2,908
  • 5
  • 33
  • 60