假设我有user
个对象,该对象的编号为id
,数组为roles
:
const user = {
id: 1,
roles: [ 'admin' ]
};
如果满足以下条件,则该对象的验证应通过:
id
与某个外部值匹配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`)
答案 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'))
})
});