【问题标题】:Joi - how to check when other key's value is null/emptyJoi - 如何检查其他键的值何时为空/空
【发布时间】:2021-10-12 18:31:28
【问题描述】:

我在尝试验证 JSON 文件时遇到问题,更具体地说,我遇到了 when 条件问题。

我有一个 a 键,它必须是过去的日期,不是必需的。然后我有一个 b 键,它应该是一个 url 并且 if a 为空/空, b 可以为空,否则必填

为了清楚起见,我将在下面留下我的代码,但现在如果 b 为空但 a 不为空,我不会收到任何错误。

a: Joi.date().less("now").raw().optional().allow(null, ""),
b: Joi.string()
  .uri({ scheme: [/https?/] })
  .when("a", {
    is: Joi.any().empty(),
    then: Joi.optional().allow(null, ""),
    otherwise: Joi.required(),
  }),

【问题讨论】:

    标签: javascript node.js validation schema joi


    【解决方案1】:

    找到了解决办法,我的条件不对。

    而不是使用 is: Joi.any().empty() 我把 is: Joi.any().valid(null, "") 和它工作。

    所以解决办法是这样的:

    a: Joi.date().less("now").raw().optional().allow(null, ""),
    b: Joi.string()
      .uri({ scheme: [/https?/] })
      .when("a", {
        is: Joi.any().valid(null, ""),
        then: Joi.optional().allow(null, ""),
        otherwise: Joi.required(),
      }),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多