2

Can we add custom validations in formik YupValidationSchema which I have mentioned below ?

YupValidationSchema = () => {
        return Yup.object({
             Email: Yup.string()
            .max(256, "Length exceed 256 chars")
            .matches(EMAIL_REGEXP, "Enter a valid email address")
            .required("Email is required")
})
}

I need to add one more validation for the email field like it should accept certain domains

let domainVal = companyName.some((val) => email.includes(val));
     if(!domainVal) error('Invalid')
     else  success('Valid');

can someone help me how can we add this domain validation code in yupvalidationschema?

userrj_vj_051620
  • 147
  • 2
  • 12

1 Answers1

8

You can use the Yup test method to add a custom validation to your Email

Basic syntax: .test("test-name", "Error message", function)

return Yup.object({
             Email: Yup.string()
            .max(256, "Length exceed 256 chars")
            .matches(EMAIL_REGEXP, "Enter a valid email address")
            .required("Email is required")
            .test("email-include-domain", "Email Must include domain", (value) => companyNames.some((company) => value.includes(company));

Related Stackoverflow Post: How to get Yup to perform more than one custom validation?

Bao Huynh Lam
  • 974
  • 4
  • 12
  • When the field is empty I should get "Email is required" instead I am getting same error "Email Must include domain" ?? – userrj_vj_051620 Jun 27 '21 at 19:58
  • It seems that the order of validation is not guaranteed because Yup operations run in parallel. Check here: https://github.com/jquense/yup/issues/256 – Bao Huynh Lam Jun 27 '21 at 20:34