Comma separated email validation using Yup
Asked Answered
B

3

5

I'm trying to write a validation schema in Yup for comma separated email addresses.

So far I've created the custom validation function and added it to my schema. It's pushing comma separated user input into an array... what I want to do is validate each of these emails in the array using the built in Yup.string().email().

function invalidEmails(this: Yup.StringSchema, msg: string) {
    return this.test({
        name: "invalidEmails",
        message: msg,
        test: (value) => {
            // push email into emails array
            const emails = value.replace(/\s/g, "").split(",");
            emails.forEach((email: any) => {
                // I want to run the Yup.string().email() validation for each email
            });
        },
    });
}

Add the custom function to the addMethod

Yup.addMethod(Yup.string, "invalidEmails", invalidEmails);

Finally add it to the Yup Schema:

<Formik
    initialValues={{
        emails: ""
    }}
    validateOnBlur={true}
    validationSchema={Yup.object().shape({
        emails:
            Yup.string().checkEmails("One or more email is not valid"),
    })}
    render={(formikProps: any) => (
        <Form>
            <input name="emails" /> // email field
        </Form>
    )}
/>
Beamends answered 17/9, 2019 at 0:50 Comment(4)
See this (something to consider) github.com/jquense/yup/issues/507Kelson
See my updated answer, let me know if you need further help.Kelson
Hi. Did my answer below help you?Kelson
Please see github.com/jquense/yup/issues/564Cloots
K
9

To check a single email standalone, code looks like this, you can modify to fit in your function.

let schema = Yup.string().email();
let result = schema.isValidSync("[email protected]"); // isValidSync returns boolean

I had to deal with the below error before I discovered that there is isValid and isValidSync

Parsing error: Can not use keyword 'await' outside an async function

Kelson answered 17/9, 2019 at 15:6 Comment(0)
M
1

Ended up doing this:

const schema = yup.object().shape({
        emails: yup.string().required("At least one email is required"),
    });

const emailSchema = yup.array().of(yup.string().email());

Then, inside form validation function:

const emails = emailsInput.split(",").map((email) => email.trim());

if (!emailSchema.isValidSync(emails)) {
    // show error
    return;
}
Mealymouthed answered 17/8, 2022 at 0:25 Comment(0)
S
0

simply do this it works for me in <Formik> <FieldArray>

just put this validation in <Formik> tag.

 validationSchema={Yup.object().shape({
      hotelEmail: Yup.array()
        .of(
          Yup.object().shape({
            email: Yup.string()
              .email(errorMessages.PROVIDE_VALID_EMAIL)
              .required(errorMessages.PROVIDE_EMAIL)
              .test(
                "Validate Email",
                errorMessages.PROVIDE_VALID_EMAIL,
                (value) => {
                  const re =
                    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                  return re.test(String(value).toLowerCase())
                },
              ),
          }),
        )
    })

above code will help to validate default YUP validation and .test function is doing some enhancement in email validation by adding some more regular expression.

Sowens answered 23/8, 2021 at 8:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.