Atul
Atul

Reputation: 688

Joi - validate a property based on value of other property

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

Answers (1)

soltex
soltex

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

Related Questions