Joi validator only one of keys

别等时光非礼了梦想. 提交于 2020-07-06 20:11:02

问题


I am working on an api that should allow multiple params but for three of them I would like to allow only one of them. It easier with values for each key but I am wondering if Joi allows it too or I should add extra validation logic in my server.

In short, for keys a, b or c I want to fail any request that has more than one of the three, so:

  1. http://myapi.com/?a=value is a valid request.

  2. http://myapi.com/?b=value&c=value2 is invalid.

Thanks!


回答1:


You're looking for object.xor(peers) if exactly one of a, b, or c is required.

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

Or, object.oxor(peers) if only one of a, b, or c is allowed, but none are required.

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



回答2:


I guess I will do it with a 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(),
        },
      ),
    };

But, maybe another solution can be better.



来源:https://stackoverflow.com/questions/54695534/joi-validator-only-one-of-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!