Conditional Validation with Joi not working

95 views Asked by At

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

1

There are 1 answers

0
Joshua On

The empty string "" does not pass the validation of Joi.string(). You could use Joi.string().allow(""), or Joi.valid("") if you want to require that ward and productValue are always "" when country != "VN".