【问题标题】:Conditional validation with joi使用 joi 进行条件验证
【发布时间】:2020-10-20 07:33:38
【问题描述】:

我尝试使用 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


    【解决方案1】:

    你的描述听起来像是or constraint

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

    以下架构可以工作:

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

    【讨论】:

    • 这看起来是正确的方法。会检查的。非常感谢您指出这一点!
    猜你喜欢
    • 2020-05-11
    • 2020-08-04
    • 2020-03-01
    • 2014-12-18
    • 2022-01-25
    • 1970-01-01
    • 2020-05-08
    • 2021-11-30
    • 1970-01-01
    相关资源
    最近更新 更多