Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (e.g. '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.

like image 438
Dmytro Mysak Avatar asked Dec 08 '25 09:12

Dmytro Mysak


1 Answers

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
  });
}
like image 136
Jake Worth Avatar answered Dec 10 '25 23:12

Jake Worth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!