问题描述
我尝试使用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',then: joi.required(),otherwise: joi.optional() })
.messages({
'any.valid': 'from.not.supported.value','any.required': 'from.required'
})
感谢您的帮助! 蒂埃里
解决方法
您描述的内容听起来像是or
constraint。
...密钥之间的关系,其中需要一个对等项(并且允许多个对等项)
以下架构将起作用:
joi.object().keys({
type: joi.string().valid('val1','val2'),from: joi.string()
}).or('type','from');