简体   繁体   中英

Joi nested when validation

I am trying to validate a nested object conditionally based upon a value in the parent.

const schema = Joi.object({
    a: Joi.string(),
    b: Joi.object({
        c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Joi.number().valid(2) }),
    }),
});

const obj = {
    a: 'foo',
    b: {
        c: 2,
    },
};

In this example, I want to get an error that c must be 1, but the validation passes. I've tried with and without references, but I clearly must be misunderstanding something fundamental about how Joi works. Any help?

you need one more . in your Joi.ref() call. .. will go up to the parent tree, then another dot to signify the property. So for your case it would go to the parent .. then get the a property parent.a

Using the Joi playground this worked for me:

Joi.object({
    a: Joi.string(),
    b: Joi.object({
        c: Joi.when(Joi.ref('...a'), {
            is: 'foo',
            then: Joi.number().valid(1),
            otherwise: Joi.number().valid(2)
        })
    })
})

If you don't need Joi.ref , this would still work with ... referencing the parent's sibling, like about14sheep pointed out in their answer . I ended up doing something like this:

Joi.object({
    a: Joi.string(),
    b: Joi.object({
        c: Joi.when('...a', {
            is: 'foo',
            then: Joi.number().valid(1),
            otherwise: Joi.number().valid(2),
        }),
    }),
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM