[英]How to validate Enum String with Joi latest version?
How do I validate Enum String?如何验证枚举字符串?
I used to go with this as suggested from here: https://github.com/hapijs/joi/issues/1449我曾经使用 go 与这里的建议: 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
但是现在, Error: Method no longer accepts array arguments: valid
I could make it work using Joi.any().valid() like this, hope works for you.我可以像这样使用 Joi.any().valid() 让它工作,希望对你有用。
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()
})
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.