admin管理员组文章数量:1245834
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:
/?a=value
is a valid request./?b=value&c=value2
is invalid.
Thanks!
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:
http://myapi./?a=value
is a valid request.http://myapi./?b=value&c=value2
is invalid.
Thanks!
Share Improve this question edited Sep 2, 2019 at 5:58 DSCH asked Feb 14, 2019 at 17:02 DSCHDSCH 2,3761 gold badge20 silver badges29 bronze badges2 Answers
Reset to default 13You'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');
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.
本文标签: javascriptJoi validator only one of keysStack Overflow
版权声明:本文标题:javascript - Joi validator only one of keys - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740251508a2248588.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论