使用 joi 进行条件验证

Conditional validation with joi

我尝试用 Joi 实现条件验证。我有一个端点可以接受:

{
  from: 'abc'
}

{
  type: 'some-type'
}

如果 type 字段不存在,则 from 字段是必填的,如果 from 字段不存在,则 type 字段是必填的. type只能接受一组值。

我尝试了以下方法但没有成功:

type: joi.alternatives().conditional('from', { is: joi.string().empty(), then: joi.string().required().valid('val1', 'val2'), otherwise: joi.optional() })
  .messages({
    'any.valid': 'type.not.supported.value',
    'any.required': 'type.required'
  }),
from: joi.alternatives().conditional('type', { is: joi.string().empty(), then: joi.required(), otherwise: joi.optional() })
  .messages({
    'any.valid': 'from.not.supported.value',
    'any.required': 'from.required'
  })

感谢您的帮助! 蒂埃里

你描述的听起来像 or constraint

...a relationship between keys where one of the peers is required (and more than one is allowed)

以下架构可行:

joi.object().keys({
  type: joi.string().valid('val1', 'val2'),
  from: joi.string()
}).or('type', 'from');