Joi validate on enums as keys in a map

2.4k views Asked by At

I have a list of enums represented as strings

export const constKeys = [
  'A',
  'B',
  'C',
  ...
];

and I want to use Joi to validate that an Immutable.js Map has keys from constKeys and values of number. It looks like I can do something like

const myMapValidator = Joi.object().keys({
    A: Joi.number(),
    B: Joi.number(),
    C: Joi.number(),
});

but this method won't work well if constKeys is really long. Is there a way to just let Joi know the key has to come from constKeys and the values are numbers?

1

There are 1 answers

1
jamesw1234 On BEST ANSWER

I figured it out. You can use mapValues from lodash

const myMapValidator = Joi.object().keys(mapValues(constKeys, () => Joi.number()))