如何验证枚举字符串?
我过去常常按照这里的建议去做: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()
})
};
但是现在,错误:方法不再接受数组参数:有效
最佳答案
我可以像这样使用 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()
});
例子:
当使用有效 Angular 色时没有错误。
const { error, value } = schema.validate({
first_name: "Magnus",
last_name: "Carlsen",
password: "chess/1234",
role: "staff"
});
console.log(error); //undefined
当没有使用 Angular 色时没有错误。
const { error, value } = schema.validate({
first_name: "Magnus",
last_name: "Carlsen",
password: "chess/1234"
});
console.log(error); //undefined
当使用不同的 Angular 色时,会出现验证错误。
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]...
关于javascript - 如何使用 Joi 最新版本验证枚举字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58486977/