Jay Shukla
Jay Shukla

Reputation: 5826

Conditional Validation with Joi not working

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

Upvotes: 0

Views: 289

Answers (1)

Joshua
Joshua

Reputation: 1

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".

Upvotes: 0

Related Questions