Reputation: 115
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!
Upvotes: 3
Views: 5847
Reputation: 74
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
Upvotes: 5
Reputation: 115
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.
Upvotes: 2