Joi when sibling 然后在 root 处添加额外的规则

Joi when sibling then add extra rules at root

我有一个复杂的验证,它会根据 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(),
});

然而,这会产生以下错误:

Error: Invalid reference exceeds the schema root: ref:type

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

我正在使用最新的 JOI (16.0.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 - 希望对您有所帮助:-)