How to use enum values with Joi String validation
node.jsValidationExpressJoinode.js Problem Overview
I am using Joi validator for my HTTP requests. There I have a parameter called type
. I need to make sure that the possible values for the parameter are either "ios" or "android".
How can I do that?
body : {
device_key : joi.string().required(),
type : joi.string().required()
}
node.js Solutions
Solution 1 - node.js
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]]
Solution 2 - node.js
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);
Solution 3 - node.js
I am late for this answer. But following will helpful for others, who wants to use enum values with Joi String validation :
function validateBody(bodyPayload) {
const schema = Joi.object({
device_key : Joi.string().required(),
type : Joi.string().valid('ios','android'),
});
return schema.validate(admin);
}
const bodyPayload = {device_key:"abc", type: "web"};
const result = validateBody(bodyPayload);
> reference : https://hapi.dev/module/joi/api/#anyallowvalues
Solution 4 - node.js
function getEnumValues<T extends string | number>(e: any): T[] {
return typeof e === 'object' ? Object.values(e) : [];
}
Joi.string().valid(...getEnumValues(YOUR_ENUM));
Solution 5 - node.js
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));