joi
joi copied to clipboard
Custom error message for each validation step.
Context
- node version: 16.4.0
- module version: 17.5.0
- environment (e.g. node, browser, native): node
- used with (e.g. hapi application, another framework, standalone, ...): nestjs
- any other relevant information:
How can we help?
Is there a better way to set custom error messages for each validation? Similar to Yup, is it possible to add custom messages in the validation function itself .string().required('Custom required message'). I can see the point to add all custom messages for the schema in a separate property where all messages can be accessed, but having this feature could be easy for understanding validations and their error messages.
// Current implementation
const schema = Joi.object({
username: Joi.string()
.min(3)
.max(30)
.required()
.messages({
"string.min": "Must have at least 3 characters",
"string.min": "Must have max 30 characters",
"string.required": "This is required"
})
};
// Is something like this possible?
const schema = Joi.object({
username: Joi.string()
.min(3, (len) => `Must have at least ${len} characters.`))
.max(30, (len) => `Must have max ${len} characters.`))
.required("This is required")
};
The second option looks more readable and clear to me. Is there an option to achieve this?
looks like you have a typo here "string.min": "Must have max 30 characters", :
username: Joi.string()
.min(3)
.max(30)
.required()
.messages({
"string.min": "Must have at least 3 characters",
"string.max": "Must have max 30 characters",
"string.required": "This is required"
})
};