I have a two fields phone field and phoneCode field. I'm using "@hapi/joi" 16.1.8 version along with expressjs.
For custom error message I used .messages() method instead of .error() because its smiply straight foreward. This is the code I tried to validate with the Joi system:
const data = { phone, phoneCode };
const schema = Joi.object({
phone: Joi.string().pattern(/^[0-9]{10}$/).required().messages({
"string.base": "Sorry! It looks like something went wrong. Please try later.",
"string.pattern.base": "Phone number must be a 10 digits number.",
"string.empty": "Phone Number is not allowed to be empty."
}),
phoneCode: Joi.string().max(3).required().messages({
"number": "Want to send default message if any error"
})
});
let validate = schema.validate(data, { abortEarly: false });
I wanted to send only one default message whenerver error occoured in phoneCode keys. I also tried
"number.*": "Want to send default message if any error"
OR
Joi.string().max(3).required().message("Want to send default message if any error") // It give Error: Cannot apply rules to empty ruleset
OR
phoneCode: Joi.string().max(3).message("Want to send default message if any error" ).required() // This worked upto a limit, not working if i sent phoneCode empty.
This is how I achieved the custom error message in JOI. Simply get the message from validate object. Its simple and working good.
const data = { phone, phoneCode };
const schema = Joi.object({
phone: Joi.string().pattern(/^[0-9]{10}$/).required().messages({
"string.base": "Sorry! It looks like something went wrong. Please try later",
"string.pattern.base": "Phone number must be a 10 digits number",
"string.empty": "Phone Number is not allowed to be empty",
"any.required": "Phone Number is required"
}),
phoneCode: Joi.string().max(3).required().messages({
"string.base": "Phone code must be valid",
"string.empty": "Phone code must be valid",
"string.max": "Phone code must be valid",
"any.required": "Phone code must be valid"
})
});
let validate = schema.validate(data);
if (!validate || validate.hasOwnProperty("error")) {
console.error(`[URL: ${req.originalUrl}] [ERROR:${JSON.stringify(validate.error.details)}]`);
return SendResponse.sendErrorMessage(res, validate.error.details[0].message);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With