How do I validate Enum String?
I used to go with this as suggested from here: https://github.com/hapijs/joi/issues/1449
enum UserRole {
Admin = 'admin',
Staff = 'staff'
}
const validator = {
create: Joi.object().keys({
first_name: Joi.string().min(1),
last_name: Joi.string()
.min(1)
.required(),
password: Joi.string()
.regex(/^[\x20-\x7E]+$/)
.min(8)
.max(72)
.required(),
role: Joi.string()
.valid([UserRole.Admin, UserRole.Staff])
.optional(),
is_active: Joi.boolean().optional()
})
};
But now, Error: Method no longer accepts array arguments: valid
I could make it work using Joi.any().valid() like this, hope works for you.
const Joi = require("@hapi/joi");
const roles = ["admin", "staff"];
const schema = Joi.object({
first_name: Joi.string().min(1),
last_name: Joi.string()
.min(1)
.required(),
password: Joi.string()
.regex(/^[\x20-\x7E]+$/)
.min(8)
.max(72)
.required(),
role: Joi.any().valid(...roles),
is_active: Joi.boolean().optional()
});
Examples:
when a valid role is used no error.
const { error, value } = schema.validate({
first_name: "Magnus",
last_name: "Carlsen",
password: "chess/1234",
role: "staff"
});
console.log(error); //undefined
when no role is used no error.
const { error, value } = schema.validate({
first_name: "Magnus",
last_name: "Carlsen",
password: "chess/1234"
});
console.log(error); //undefined
when a different role is used it gives validation error.
const { error, value } = schema.validate({
first_name: "Magnus",
last_name: "Carlsen",
password: "chess/1234",
role: "unknown"
});
console.log(error); // Error [ValidationError]: "role" must be one of [admin, staff]...
enum UserRole {
Admin = 'admin',
Staff = 'staff'
}
const validator = {
create: Joi.object().keys({
first_name: Joi.string().min(1),
last_name: Joi.string()
.min(1)
.required(),
password: Joi.string()
.regex(/^[\x20-\x7E]+$/)
.min(8)
.max(72)
.required(),
role: Joi.string()
.valid(UserRole.Admin, UserRole.Staff) // do not use an array
.optional(),
is_active: Joi.boolean().optional()
})
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.