我还有另一种方法来检查每个验证错误。如果你有一个验证,不管条件是什么,你都可以这样做:
username: Joi.string() // It has to be string
.label("Username") // The label
.error(new Error('It is whatever error')) // Custom general error
您也可以使用箭头功能执行此操作:
username: Joi.string() // It has to be string
.label("Username") // The label
.error(() => 'It is whatever error') // Custom general error
但是如果有一些验证参数和错误,我们有这些解决方案:
password: Joi.string() // It has to be string
.min(8) // It has to have at least 8 characters
.required() // It has to have a value
.label("Password") // The label
.error(errors => {
return errors.map(err => { // Here we map the errors (ES6) discover within an array
if (err.type === "string.min") { // Check the type of error e.g: 'string.min,any.empty,number.min,...'
return { message: "The length of the parameter should be more than 8 characters" }; // Which message we want to display
} else {
return { message: "another validation error" };
}
});
})
Switch Case 还有另一种解决方案:
password: Joi.string() // It has to be string
.min(8) // It has to have at least 8 characters
.required() // It has to have a value
.label("Password") // The label
.error(errors => {
return errors.map(err => { // Here we map the errors (ES6) discover within an array
switch (err.type) {
case "string.min":
return { message: "The length of the parameter should be more than 8 characters" }; // Which message we want to display
case "any.empty":
return { message: "The parameter should have a value" };
}
});
})
请注意,如果其中一个验证错误未指定您有错误,则 err.type未定义。
您可以在消息中使用err.context以动态显示标签、限制、最大值、...:
message: `${err.context.label} must have at least ${err.context.limit} characters.`
参考:Joi 文档