简体   繁体   English

Joi中可选条件的模式

[英]Schema for optional conditions in Joi

Suppose I have an object like: 假设我有一个像这样的对象:

{
  a : 1,
  b : 2,
  c : 3,
  d : 4
}

At least 1 of pair out of [a,b], [a,c], [d] should have validation passed(have correct values). [a,b], [a,c], [d] 至少一对应该通过验证(具有正确的值)。

Assume all values are numbers . 假设所有值都是数字

How can I create Joi schema for it. 如何为它创建Joi架构。

You can use Joi.alternatives() and create a Joi schema like this: 您可以使用Joi.alternatives()并创建一个这样的Joi架构:

Joi.alternatives().try(
    Joi.object({
        a: Joi.number().required(),
        b: Joi.number().required(),
        c: Joi.number(),
        d: Joi.number()
    }),
    Joi.object({
        a: Joi.number().required(),
        b: Joi.number(),
        c: Joi.number().required(),
        d: Joi.number()
    }),
    Joi.object({
        a: Joi.number(),
        b: Joi.number(),
        c: Joi.number(),
        d: Joi.number().required()
    }),
)

There is another alternative that uses .requiredKeys() and simplies the code above : 还有另一种替代方法使用.requiredKeys ()并简化上面的代码:

const JoiObjectKeys = {
    a: Joi.number(),
    b: Joi.number(),
    c: Joi.number(),
    d: Joi.number()
}

Joi.alternatives().try(
    Joi.object(JoiObjectKeys).requiredKeys('a', 'b'),
    Joi.object(JoiObjectKeys).requiredKeys('a', 'c'),
    Joi.object(JoiObjectKeys).requiredKeys('d'),
);

With this schema you will get this results: 使用此架构,您将获得以下结果:

{ a: 1 } > fails
{ b: 1 } > fails
{ c: 1 } > fails
{ a: 1, b: 1 } > passes
{ a: 1: c: 1 } > passes
{ d: 1 } > passes
{ d: 1, a: 1 } > passes

Be careful with using Joi.number() . 小心使用Joi.number() It will also consider '3' to be valid — without actually turning it into the number 3 if you're using Joi.assert . 它也会认为'3'是有效的 - 如果你使用的是Joi.assert它实际上并没有把它变成3 Joi.assert To avoid that, you should probably add the .strict() modifier. 为避免这种情况,您应该添加.strict()修饰符。

See https://medium.com/east-pole/surprised-by-joi-35a3558eda30 请参阅https://medium.com/east-pole/surprised-by-joi-35a3558eda30

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

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