How to use enum values with Joi String validation
You can use valid
.
const schema = Joi.object().keys({ type: Joi.string().valid('ios', 'android'),});const myObj = { type: 'none' };const result = Joi.validate(myObj, schema);console.log(result);
This gives an error ValidationError: child "type" fails because ["type" must be one of [ios, android]]
Maybe it will be useful for anyone who wants to check values based on existing enum/array of values.
const SomeEnumType = { TypeA: 'A', TypeB: 'B' };
Then just use this:
const schema = Joi.object().keys({ type: Joi.string().valid(...Object.values(SomeEnumType)),});const myObj = { type: 'none' };const result = Joi.validate(myObj, schema);
For typescript users,
getEnumValues<T extends string | number>(e: any): T[] { return typeof e === 'object' ? Object.keys(e).map(key => e[key]) : [];}Joi.string().valid(...getEnumValues(YOUR_ENUM));