13

Is there a way I can validate a value like this with Joi so that I can verify it is an object with zero or more keys (of any name) and that each have values of either a string, number or boolean?

{
  dynamicallyNamedKey1: 'some value',
  dynamicallyNamedKey2: 4
}
Iain J. Reid
  • 978
  • 1
  • 11
  • 23
1977
  • 2,580
  • 6
  • 26
  • 37

1 Answers1

17

You're going to want to use Joi's object().pattern() method. It's specifically for validating objects with unknown keys.

To match against one or more datatypes on a single key you'll need alternatives().try() (or simply pass an array of Joi types).

So the rule to match your needs would be:

Joi.object().pattern(/^/, Joi.alternatives().try(Joi.string(), Joi.number(), Joi.boolean()))
Ankh
  • 5,478
  • 3
  • 36
  • 40
  • 4
    Note that a simple array `[]` is a shortcut for `Joi.alternatives()`. So you can just do: `Joi.object().pattern(/^/, [Joi.string(), Joi.number()])` – Christophe Marois Apr 23 '17 at 00:22