简体   繁体   中英

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?

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?

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