javascript - Joi 验证器只有一个键

标签 javascript node.js joi

我正在开发一个应该允许多个参数的 api,但对于其中的三个,我只想允许其中一个。 每个键的值更容易,但我想知道 Joi 是否也允许它,或者我应该在我的服务器中添加额外的验证逻辑。

简而言之,对于键 abc 我想使任何具有三个以上之一的请求失败,所以:

  1. http://myapi.com/?a=value有效请求。

  2. http://myapi.com/?b=value&c=value2 无效

谢谢!

最佳答案

您正在寻找 object.xor(peers)如果恰好需要 abc 之一。

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)如果仅允许 abc 之一,但都不是必需的。

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/

相关文章:

javascript - 您如何设计或覆盖下拉菜单的默认悬停颜色?

javascript - 使用 CSS/Javascript 突出显示溢出

validation - 如何根据上下文中的值创建 Joi `when` 条件?

javascript - Joi 验证 : multiple validation error messages for single field

JavaScript:我自己的解析器的动态正则表达式

javascript - Eloquent javascript 第 4 章计算相关性

javascript - 什么是 html 模板中的自上而下/自下而上包含

node.js - fs.readdirSync 包含子目录

node.js - Typescript - Node js - const 声明中缺少初始化程序

javascript - 如何使用 Joi 验证其键应与外部对象的另一个键(其值为数组的键)匹配的嵌套对象?