Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi - Required based on value on other key

Tags:

node.js

joi

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: ''
}
like image 845
Salar Avatar asked Nov 30 '19 09:11

Salar


1 Answers

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

when('image', {
  is: Joi.exist(),
  then: Joi.string().allow(''),
  otherwise: Joi.string().required(),
})
like image 159
James Avatar answered Sep 27 '22 20:09

James