Joi 验证器只有一个键

Joi validator only one of keys

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

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

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

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

谢谢!

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

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,但需要 none。

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');

我想我会用Joi.try。

const one_of_them = {
      query: Joi.alternatives().try(
        {
          a: Joi.string().required(),
          b: Joi.string().invalid().required(),
          c: Joi.string().invalid().required(),
        },
        {
          b: Joi.string().required(),
          a: Joi.string().invalid().required(),
          c: Joi.string().invalid().required(),
        },
        {
          c: Joi.string().required(),
          a: Joi.string().invalid().required(),
          b: Joi.string().invalid().required(),
        },
      ),
    };

但是,也许另一个解决方案会更好。