首页 > 解决方案 > 使用 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'
  })

谢谢你的帮助!蒂埃里

标签: joi

解决方案


你所描述的听起来像是一个or约束

...需要其中一个对等点(并且允许多个对等点)的键之间的关系

以下架构将起作用:

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

推荐阅读