【问题标题】:How to force an attribute to be present only if another one is true?仅当另一个属性为真时,如何强制存在一个属性?
【发布时间】:2018-12-16 04:31:16
【问题描述】:

我正在尝试使用 Joi 验证一个简单的对象。我定义的架构如下:

const singleReq = Joi.object({  
    subscribing: Joi.boolean(),  
    duration: Joi.number().integer().positive(),
});

我希望 duration 仅在 subscribing 为真时出现(不为空)。我试图用断言来做,但我不知道怎么做。

【问题讨论】:

    标签: javascript joi


    【解决方案1】:

    您可以尝试以下方法:

    const singleReq = Joi.object({  
      subscribing: Joi.boolean(),  
      duration: Joi.number()
      .when('subscribing', { is: true, then: Joi.integer().positive().required() })
    });
    

    如果你想改变类型,你也可以尝试使用下面的例子:

    const schema = {
      a: Joi.alternatives().when('b', { is: 5, then: Joi.string(), otherwise: Joi.number() }),
      b: Joi.any()
    };
    

    references

    【讨论】:

    • 谢谢!这正是我所需要的!
    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多