简体   繁体   English

Joi 在验证时嵌套

[英]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.在这个例子中,我想得到一个 c 必须为 1 的错误,但是验证通过了。 I've tried with and without references, but I clearly must be misunderstanding something fundamental about how Joi works.我尝试过使用和不使用参考文献,但显然我一定是误解了有关 Joi 工作原理的一些基本知识。 Any help?有什么帮助吗?

you need one more .你还需要一个. in your Joi.ref() call.在您的Joi.ref()调用中。 .. 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所以对于你的情况,它会去父..然后得到一个属性parent.a

Using the Joi playground this worked for me:使用Joi playground这对我有用:

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 .如果您不需要Joi.ref ,这仍然适用于...引用父母的兄弟姐妹,就像about14sheep在他们的回答中指出的那样。 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),
        }),
    }),
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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