Search code examples
node.jsjoi

Joi - Required based on value on other key


I want to validate an input which only has two fields(namely text and image). Both text and image are string and one of them must always be present. When one of the fields is absent then the other one can not be an empty string. this is the Validation I have defined.

text: Joi.string()
    .when('image',
        {
            is: Joi.string(),
            then: Joi.string().allow(''),
            otherwise: Joi.string().required(),
        }
    ),
image: Joi.string().allow(null),

when I use the below input, the validation allows the data to pass. I dont how to change the validation to prohibit the below input.

post: {
    text: ''
}

Solution

  • Use exist() instead of string() when validating:

    when('image', {
      is: Joi.exist(),
      then: Joi.string().allow(''),
      otherwise: Joi.string().required(),
    })