Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
    )}
/>
like image 784
blankface Avatar asked Sep 07 '26 23:09

blankface


2 Answers

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

like image 87
Hassan Voyeau Avatar answered Sep 11 '26 02:09

Hassan Voyeau


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;
}
like image 32
Emre Avatar answered Sep 11 '26 00:09

Emre