Joi validation not validating required fields

I have 4 fields that I’m trying to validate using Joi. I want the following to be required: Either first or second, And third or fourth.

so one of the following should pass but nothing else should:

{first: 'yo', third: true}
// or
{second: 'bro', third: true}
// or
{first: 'yo', fourth: true}
// or
{second: 'bro', fourth: true}

I tried the following but it’s letting third and fourth be blank.

function validate(data) {
    const schema = Joi.object({
        first: Joi.string(),
        second: Joi.string(),
        third: Joi.boolean(),
        fourth: Joi.boolean(),
    })
        .xor('first', 'second')
        .xor('third', 'fourth');

    return schema.validate(data);
}

88 thoughts on “Joi validation not validating required fields”

Leave a Comment