简体   繁体   English

Joi - 对特定条件使用“有效”

[英]Joi - use 'valid' for specific condition

I try to validate the query parameter userId.我尝试验证查询参数 userId。

If a user is an admin then he can use any user id.如果用户是管理员,则他可以使用任何用户 ID。

If no - then use the only id from a specific array.如果没有 - 则使用特定数组中的唯一 id。

const validUserIds = isUserAdmin ? req.query.userId : userIds;
const schema = Joi.object().keys({
    userId: Joi.string().optional().regex(UUIDRegex).valid(validUserIds),
  });
Joi.validate(req.query, schema).then(.....);

Problem: When we send bad user id (eg 'abc' etc, regex validation should fail) and the user is the admin then validation pass successfully.问题:当我们发送错误的用户 ID(例如“abc”等,正则表达式验证应该失败)并且用户是管理员时,验证成功通过。

Can I create something like this: if the user is the admin then validate only by rexeg if no - validate by regex + valid id list.我可以创建这样的东西:如果用户是管理员,则仅通过 rexeg 验证,如果没有 - 通过正则表达式 + 有效 ID 列表验证。

Joi.when sounds like the right function here. Joi.when在这里听起来是正确的功能。

userId: Joi.string()
  .regex(UUIDRegex)
  .when('isUserAdmin', {
    is: false,
    then: yourValidateUserIdFunction() // validate
  });

Reading through this, we check if the user ID is a string, then we check that it matches the UUIDRegex for all users, and finally we check if the user ID is valid when the user is not an admin. UUIDRegex ,我们检查用户 ID 是否为字符串,然后我们检查它是否与所有用户的UUIDRegex匹配,最后我们检查用户 ID 在用户不是管理员时是否有效。

Alternatively, if isUserAdmin is outside of the Joi schema, create two different schemas based on that information:或者,如果isUserAdmin在 Joi 架构之外,则根据该信息创建两个不同的架构:

const isUserAdmin = true;
if (isAdmin) {
  joi.object({
    userId: Joi.string().regex(UUIDRegex),
  });
} else {
  joi.object({
    userId: Joi.string().regex(UUIDRegex).validateUserId(), // validate
  });
}

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

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