[英]Joi custom error for each validation option
I have Joi
schema and want to specify a custom error message for each of the options.我有
Joi
架构,想为每个选项指定一个自定义错误消息。
Example of my schema:我的架构示例:
const schema = Joi.object().keys({
name: Joi.string()
.min(5).error(() => 'first message')
.max(25).error(() => 'second message')
.required().error(() => 'third message')
)}
At the moment this validation works in such way: if whatever of the option is invalid only third message appears.目前,此验证以这种方式工作:如果任何选项无效,则仅显示第三条消息。
Expected behavior - error message appears according to which option is invalid (as default Joi behavior, but with my custom error message).预期行为 - 根据哪个选项无效显示错误消息(作为默认的 Joi 行为,但带有我的自定义错误消息)。
Thanks in regards!谢谢你的问候!
const schema = Joi.object().keys({
title: Joi.string()
.min(5)
.max(25)
.required()
.messages({
"string.min": "first msg",
"string.max": "second msg",
"any.empty":"third msg"
})
})
These is the best way to show custom error messages这些是显示自定义错误消息的最佳方式
For my situation I just found such solution:对于我的情况,我刚刚找到了这样的解决方案:
const schema = Joi.object().keys({
title: Joi.string()
.min(5)
.max(25)
.required()
.error((errors) => {
return errors.map(error => {
switch (error.type) {
case "string.min":
return { message: "first msg" };
case "string.max":
return { message: "second msg" };
case "any.empty":
return { message: "third msg" };
}
}
)
})
Seems not the best one, as it cause too many code, especialy if you have big form, hovewer it works as I desire.似乎不是最好的,因为它会导致太多的代码,特别是如果你有很大的形式,但是它可以按我的意愿工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.