【问题标题】:Joi: how to validate only one of two keys (with array)?Joi:如何仅验证两个键中的一个(带数组)?
【发布时间】:2020-04-08 09:49:38
【问题描述】:

假设我有 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`)

【问题讨论】:

    标签: javascript validation joi


    【解决方案1】:

    我找到了答案,这个场景可以使用when操作来完成:

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

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      • 2017-07-28
      • 2019-04-07
      相关资源
      最近更新 更多