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?

Answer

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) => companyName.some((val) => value.includes(val));

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