I want to define some attributes in my json schema conditionally for different countries. Below is what I'm trying but somehow its not working.
Joi.object({
country: Joi.string().required(),
productValue: Joi.when(".country", {
is: "VN",
then: Joi.number().required(),
otherwise: Joi.string()
}),
pickUpDetails: Joi.object().keys({
ward: Joi.when(Joi.ref('country'), {
is: "VN",
then: Joi.string().required(),
otherwise: Joi.string()
})
}),
})
The sample JSON I'm validating against above schema is below:
{
"country": "ID",
"productValue": "",
"pickUpDetails": {
"ward": ""
}
}
As per my understanding and expected is that the above JSON should be valid since the country value I'm passing is ID not VN. Can anyone please help with it?
Playground to test it here
The empty string
""
does not pass the validation ofJoi.string()
. You could useJoi.string().allow("")
, orJoi.valid("")
if you want to require thatward
andproductValue
are always""
whencountry != "VN"
.