Reputation: 688
I want to conditionally check the os.disk_size
property based on the image.offer
property.
If image.offer
is windows
then os.disk_size>= 64
for all other cases os.disk_size>=30
Sample data below
{
"resource": {
"vms": {
"v1": {
"os": {
"disk_size": 30
},
"image": {
"offer": "ubuntu"
},
},
"v2": {
"os": {
"disk_size": 50
},
"image": {
"offer": "CentOS"
}
},
"v3": {
"os": {
"disk_size": 64
},
"image": {
"offer": "windows"
}
}
}
}
}
Sample validation:
I am using "joi": "^13.1.2"
const schemas = {
resource: {
vms: Joi.object({
image: Joi.object({
offer: Joi.string().required()
}).optional(),
os: Joi.object({
disk_size: Joi.number().required()
}).required(),
}),
}
};
Upvotes: 1
Views: 1317
Reputation: 3531
Your schema is not considering object keys v1
, v2
and v3
.
To consider those keys and follow the pattern v + number
, you can use Joi.pattern with a regex /v\d/
:
Joi.object().pattern(/v\d/, ...)
This means the key should start with a v
and end with a number.
Then you can use Joi.when combined with ref to achieve your condition:
Joi.object({
resource: Joi.object({
vms: Joi.object().pattern(
/v\d/,
Joi.object({
image: Joi.object({
offer: Joi.string().required(),
}).optional(),
os: Joi.object({
disk_size: Joi.when(Joi.ref("...image.offer"), {
is: "windows",
then: Joi.number().min(64),
otherwise: Joi.number().min(30),
}),
}).required(),
})
),
}),
});
Upvotes: 4