How do I access another field's value in Joi validation?

Viewed 341

How do I access another field value while I am validating a field?

export const validation = {
  body: Joi.object({
    name: Joi.string()
      .required()
      .min(2)
      .max(20)
    email: Joi
      .string()
      .required()
      .email()
      .pattern(new Regex()) // access value name here
      .when('name', {
       is: Joi.required(),
       then: // access value of name here
      }),
  }),
}

In this case, I want to access the name field value in email field validation.

1 Answers

You can use the custom function to access the values of an object in the schema

export const validation = {
  body: Joi.object({
    name: Joi.string()
      .required()
      .min(2)
      .max(20)
    email: Joi
      .string()
      .required()
      .email()
      }).custom((user, helpers) => {
      const { email, name} = user;
      
      if (your regex validation on email) {
        // if email validation failed
        return helpers.message({
          custom: `invalid email`
        });
      }
      if (email !== `${name}@example.com`) {
        // if name validation failed
        return helpers.message({
          custom: `email must be ${name}@example.com`
        });
      }
      
      return user;
    }),
  }),
}
Related