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>
)}
/>
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With