Reputation: 5
I have a simple schema with multiple keys a,b,c,d , all of them are string . i want to validate such that between a and b only 1 of them should be present at a time. and the same for c and d
I am using the xor validation that Joi provides to achieve that but I want to set a custom message for each xor group when it fails. sadly i am only getting the custom message of the last xor for whichever group errors out.
const schema = Joi.object({
a: Joi.string(),
b: Joi.string(),
c: Joi.string(),
d: Joi.string()
})
.xor("a", "b")
.messages({
"object.xor": "either a or b must be present but not both "
})
.xor("c", "d")
.messages({
"object.xor": "either c or d must be present but not both "
});
const data = {
a: "not-empty",
b: "not-empty",
c: "not-empty",
d: "not-empty"
};
const result = schema.validate(data, {
abortEarly: false
});
I get the below output
{
value: { a: 'not-empty', b: 'not-empty', c: 'not-empty', d: 'not-empty' },
error: [Error [ValidationError]: either c or d must be present but not both ] {
_original: { a: 'not-empty', b: 'not-empty', c: 'not-empty', d: 'not-empty' },
details: [ [Object], [Object] ]
}
}
I expected it to throw error for both a and b and as well as c and d group . But i could only get the last message . Please let me know if there is any other way i can set custom message for each xor validation.
Upvotes: 0
Views: 34