Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we add custom validations in formik YupValidationSchema?

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?

like image 599
userrj_vj_051620 Avatar asked Oct 29 '25 14:10

userrj_vj_051620


1 Answers

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?

like image 74
Bao Huynh Avatar answered Oct 31 '25 03:10

Bao Huynh



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!