简体   繁体   English

Joi:如何仅验证两个键之一(带数组)?

[英]Joi: how to validate only one of two keys (with array)?

Let's say I have user object with id number and roles array:假设我有user object 的id号和roles数组:

const user = {
  id: 1,
  roles: [ 'admin' ]
};

And validation of this object should pass if:如果满足以下条件,则应通过此 object 的验证:

  1. id is matching some external value id匹配一些外部值
  2. OR roles includes admin string OR roles包括admin字符串

I've tried this approach but it doesn't work as expected:我已经尝试过这种方法,但它没有按预期工作:

const schema = Joi.object({
  id: Joi.number().valid(Joi.ref('$userId')), // shouldn't pass as $userId === 2
  roles: Joi.array().has(Joi.string().valid('admin')) // should pass as user has 'admin' role
}).or('id');

schema.validate(user, {
  context: {
    userId: 2
  }
}); // should pass as `user` includes `admin` in `roles` (but `userId` not equals `user.id`)

I found an answer, this scenario can be accomplished using when operation:我找到了答案,这个场景可以使用when操作来完成:

Joi.object({
  id: Joi.number(),
  roles: Joi.array().when('id', { 
    not: Joi.ref('$userId'), 
    then: Joi.array().has(Joi.string().valid('admin'))
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM