admin管理员组文章数量:1323335
I have Joi
schema and want to specify a custom error message for each of the options.
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).
Thanks in regards!
I have Joi
schema and want to specify a custom error message for each of the options.
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).
Thanks in regards!
Share asked Mar 1, 2019 at 19:37 Orest BatsOrest Bats 1151 silver badge10 bronze badges2 Answers
Reset to default 5const 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.
本文标签: javascriptJoi custom error for each validation optionStack Overflow
版权声明:本文标题:javascript - Joi custom error for each validation option - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742137606a2422439.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论