【问题标题】:Schema for optional conditions in JoiJoi 中可选条件的模式
【发布时间】:2019-10-08 16:08:23
【问题描述】:

假设我有一个像这样的对象:

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

[a,b], [a,c], [d] 中的至少一对应该通过验证(具有正确的值)。

假设所有值都是数字

如何为它创建 Joi 架构。

【问题讨论】:

    标签: javascript joi


    【解决方案1】:

    小心使用Joi.number()。它还将认为'3' 是有效的——如果您使用Joi.assert,则实际上不会将其转换为数字3。为避免这种情况,您可能应该添加 .strict() 修饰符。

    https://medium.com/east-pole/surprised-by-joi-35a3558eda30

    【讨论】:

      【解决方案2】:

      您可以使用 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()
          }),
      )
      

      还有另一种选择,使用 .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'),
      );
      

      使用此架构,您将获得以下结果:

      { 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
      

      【讨论】:

        猜你喜欢
        • 2020-05-08
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-12
        • 1970-01-01
        • 1970-01-01
        • 2020-07-02
        相关资源
        最近更新 更多