Reputation: 2038
I am new to NodeJS and need help. I am using JOI as schema validation and I need to have the custom message for each validation. Like if min(3) is there I want custom message and if same field has required then I want different custom message for that.
Please suggest link to any example where I can achieve this. Below is what I was trying.
const schema = {
name: Joi.string().min(3).error((error) => "Min 3 Characters").required().error((error) => "Field is required")
};
Upvotes: 1
Views: 12378
Reputation: 1356
According to the documentation you could do something like this:
const schema = Joi.string().error(new Error('Was REALLY expecting a string'));
schema.validate(3); // returns Error('Was REALLY expecting a string')
Upvotes: 0
Reputation: 399
You can do:
const schema = {
name: Joi.string()
.min(3)
.required()
.options({
language: {
any: { required: 'is required' },
string: { min: 'must be at least 3 Characters' },
},
}),
}
Upvotes: 3
Reputation: 2790
add error to the end of your validation.
var schema = Joi.object().keys({
firstName: Joi.string().min(5).max(10).required().error(new Error('Give your error message here for first name')),
lastName: Joi.string().min(5).max(10).required().error(new Error('Give your error message here for last name'))
..
});
there is also more stuff you can do if you explore the error function
firstname: Joi.string()
.max(30)
.min(5)
.required()
.label('First Name')
.error((err) => {
const errs = err.map(x => `${x.flags.label} ${x.type}(${x.context.limit}) with value ${x.context.value}`);
console.log(errs);
return errs.toString();
})
Upvotes: 2