最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Joi nested when validation - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Feb 18, 2022 at 0:16 ml-learnerml-learner 932 silver badges6 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 9

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),
        }),
    }),
});
发布评论

评论列表(0)

  1. 暂无评论