Search code examples
javascriptvalidationjoi

Making a field required in joi only when specific fields are filled


I need to define a field required only when a list of fields are filled, otherwise the field is optional.

I tried with when, but I'm confuse with the result :

const schema = Joi.object({
  one: Joi.string(),
  two: Joi.string().when(
    Joi.object({
      one: Joi.required(),
      three: Joi.required(),
    }),
    {
      then: Joi.required()
    }
  ),
  three: Joi.string(),
});

schema.validate({one: undefined, two: undefined, three: undefined}); 
// return ValidationError: "two" is required

Any idea what is wrong with the schema?

I use Joi 17.11.0


Solution

  • It will work with conditional checking but it looks a bit ugly, though.

    • .when('one', { ... })
    • .when('three', { ... })

    const schema = joi.object({
      one: joi.string(),
      two: joi.string().when('one', {
        is: joi.exist(),
        then: joi.when('three', {
          is: joi.exist(),
          then: joi.required(),
          otherwise: joi.optional()
        }),
        otherwise: joi.optional()
      }),
      three: joi.string(),
    });
    
    // Test cases
    console.log(schema.validate({one: 'value1', two: 'value2', three: 'value3'})); // Should be valid
    console.log(schema.validate({one: undefined, two: undefined, three: undefined})); // Should be valid
    console.log(schema.validate({one: 'value1', two: undefined, three: 'value3'})); // Should be invalid
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/joi-browser.min.js"></script>