I have been trying to get nested where validations, but no luck so far. Here's what I want to achieve:
1- If mainType is COMMERCIAL then define required schema for contactMethod. 2- If isHousing is true then define required schema for contactMethod. 3- If mainType is REAL_ESTATE then disallow passing the contactMethod object
Here are my failed attempts:
contactMethod: Joi.when('mainType', {
is: 'COMMERCIAL',
then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),
}).required(),
})
.required()),
}).when('isHousing', {
is: true,
then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),
}).required(),
})
.required(),
otherwise: Joi.disallow(),
})
I also tried this:
contactMethod: Joi.when('mainType', {
switch: [
{
is: 'COMMERCIAL',
then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),
}).required(),
})
.required(),
},
{
is: 'REAL_ESTATE',
then: Joi.when('isHousing', {
is: true,
then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),
}).required(),
})
.required(),
}),
otherwise: Joi.disallow(),
},
],
})
So what am I doing wrong here?
Okay, so here's how I solved it:
contactMethod: Joi.when('mainType', {
is: 'COMMERCIAL',
then: Joi.object()
.keys({
create: Joi.object()
.keys({
message: Joi.string().allow(''),
})
.required(),
})
.required(),
otherwise: Joi.when('isHousing', {
is: true,
then: Joi.object()
.keys({
create: Joi.object()
.keys({
message: Joi.string().allow(''),
})
.required(),
})
.required(),
otherwise: Joi.forbidden(),
}),
})
My attempts didn't include the keys({}) as suggested by @hoangdv above + I also needed to change disallow() to forbidden.
Hope this helps somebody in the future.