简体   繁体   中英

Joi - use 'valid' for specific condition

I try to validate the query parameter userId.

If a user is an admin then he can use any user id.

If no - then use the only id from a specific array.

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.

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.

Joi.when sounds like the right function here.

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.

Alternatively, if isUserAdmin is outside of the Joi schema, create two different schemas based on that information:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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