blankface
blankface

Reputation: 6347

Comma separated email validation using Yup

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>
    )}
/>

Upvotes: 5

Views: 24282

Answers (3)

Emre
Emre

Reputation: 899

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;
}

Upvotes: 1

Krishna Jangid
Krishna Jangid

Reputation: 5410

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.

Upvotes: 0

Hassan Voyeau
Hassan Voyeau

Reputation: 3624

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

Upvotes: 9

Related Questions