我正在开发一个应该允许多个参数的 api,但对于其中的三个,我只想允许其中一个。 每个键的值更容易,但我想知道 Joi 是否也允许它,或者我应该在我的服务器中添加额外的验证逻辑。
简而言之,对于键 a
、b
或 c
我想使任何具有三个以上之一的请求失败,所以:
http://myapi.com/?a=value
是有效请求。http://myapi.com/?b=value&c=value2
无效。
谢谢!
最佳答案
您正在寻找 object.xor(peers)如果恰好需要 a
、b
或 c
之一。
Defines an exclusive relationship between a set of keys where one of them is required but not at the same time where:
peers
- the exclusive key names that must not appear together but where one of them is required.peers
can be a single string value, an array of string values, or each peer provided as an argument.
const schema = Joi.object().keys({
a: Joi.any(),
b: Joi.any(),
c: Joi.any()
}).xor('a', 'b', 'c');
或者,object.oxor(peers)如果仅允许 a
、b
或 c
之一,但都不是必需的。
Defines an exclusive relationship between a set of keys where only one is allowed but none are required where:
peers
- the exclusive key names that must not appear together but where none are required.
const schema = Joi.object().keys({
a: Joi.any(),
b: Joi.any(),
c: Joi.any()
}).oxor('a', 'b', 'c');
关于javascript - Joi 验证器只有一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54695534/