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