joi - 使用 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
约束。
...需要其中一个对等点(并且允许多个对等点)的键之间的关系
以下架构将起作用:
joi.object().keys({
type: joi.string().valid('val1', 'val2'),
from: joi.string()
}).or('type', 'from');
推荐阅读
- python - 如何在字符串中查找和删除日期时间,即:Sun Mar 3, 2019 07:39AM
- angular - 动态添加组件 ViewContainerRef 未定义
- javascript - 一旦客户端离开房间或断开连接,客户端不会重新连接
- jmeter - 我得到 java.net.URISyntaxException: Illegal character in query at index 220: while running a test in Jmeter
- ruby-on-rails - PG::ConnectionBad(致命:pg_hba.conf 拒绝主机“172.17.0.1”、用户“XXX”、数据库“XXX”、SSL 关闭):
- servlets - 如何将对象注入 groovy servlet?
- extend - 为什么我们不能在 vmware vSphere 云中使用快照扩展磁盘?
- ios - 如何删除 PersistentStore 并重新创建它以添加新数据?
- c# - MVC .net 控制器未从视图接收 POST 数据
- sql - 加入并获取另一个表中的最后一条记录