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

时间:2020-04-08 09:49:38

标签: javascript validation joi

假设我有user个对象,该对象的编号为id,数组为roles

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

如果满足以下条件,则该对象的验证应通过:

  1. id与某个外部值匹配
  2. roles包含admin字符串

我已经尝试过这种方法,但是不能按预期工作:

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`)

1 个答案:

答案 0 :(得分:0)

我找到了答案,可以使用when操作来实现这种情况:

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