【问题标题】:Joi when sibling then add extra rules at rootJoi 当兄弟姐妹然后在根目录添加额外的规则
【发布时间】:2020-01-16 19:30:02
【问题描述】:

我有一个复杂的验证,它会根据 JSON 中的 a 值而变化。

{ type: 'a', thing: 1, foo: 'abc' }
{ type: 'b', thing: 2, bar: 123 }

我想验证如果类型是a,则使用一组兄弟,如果是b,则使用另一组兄弟

我想使用when switch,但不知道如何在根目录下执行此操作。

Joi.object({
  type: Joi.string().valid('a','b').required(),
  thing: Joi.number().required()
}).when('type', {
  switch: [
    { is: 'a', then: Joi.object({ foo: Joi.string() }) },
    { is: 'b', then: Joi.object({ bar: Joi.number() }) },
  ],
  otherwise: Joi.forbidden(),
});

但是这会产生以下错误:

错误:无效引用超出了架构根:ref:type

这有点像错误,但我不知道如何重组它以使其在根应用选择器。

我正在使用最新的 JOI (16.0.1)

【问题讨论】:

    标签: joi


    【解决方案1】:

    这可以通过在传递给.when() 的键名前加上. 来解决,以表示该键与正在验证的对象相关:

    Joi.object({
      type: Joi.string().valid('a','b').required(),
      thing: Joi.number().required()
    })
    .when('.type', {  /* <-- prefix with . */
      switch : [
        { is: 'a', then: Joi.object({ foo: Joi.string() }) },
        { is: 'b', then: Joi.object({ bar: Joi.number() }) },]
    })
    

    这是a working example - 希望对您有所帮助:-)

    【讨论】:

    • 太棒了,这正是我所缺少的,谢谢:)
    • 不客气,好久不见!希望X公司一切顺利:)
    • 哈哈是的,一切顺利,像往常一样忙碌,你应该找个时间来 /dev/talk 跟上一下
    • 很好 - 啊,是的,现在有几个人向我提到了这一点。一定会在不久的将来出现的:)
    猜你喜欢
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    相关资源
    最近更新 更多