Reputation: 2695
Is there any way to validate multiple email id in Formik without using Yup. I have been using the following code currently for single email validation:
if (!values.cc) {
errors.cc = "Required";
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.cc)) {
errors.cc = "Invalid email address";
}
The emails will be separated by space.
Upvotes: 1
Views: 1846
Reputation: 635
use yup it's very helpful :)
email: Yup.string()
.email("Format de l'email est invalide")
.matches(
/^(([^<>()\[\]\\.,;:\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,}))$/
, "Format de l'email est invalide")
.required("Obligatoire!"),
Upvotes: 1
Reputation: 2695
I have done the validation using the following code, in this case the user need to enter multiple emails by separating them with a comma.
if (!values.cc) {
errors.cc = "Required";
} else {
let emailList = values.cc.split(",");
emailList.forEach((email) => {
if (
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i.test(email)
) {
errors.cc =
"Please provide a valid email. In case of multiple emails, seperate them with a comma (,) ";
}
});
}
Upvotes: 0
Reputation: 523
You need to make your own custom validation function for that here is an
Formik Field:
<Field
type="text"
name="email"
placeholder="Enter Your Email Address"
validate={(event) => Validators.customFieldLevelValidation(event, [Validators.required, Validators.email, Validators.aol])} />
Custom Validator Class:
class Validators {
static customFieldLevelValidation = (value, validations) => {
for (let validation of validations) {
const result = validation(value);
if (result) {
return result;
}
}
return null;
};
static required = value => (value ? undefined : 'Required');
static email = value =>
value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{1,100}$/i.test(value)
? 'Invalid email address'
: undefined;
static aol = value =>
value && /.+@aol\.com/.test(value)
? 'Really? You still use AOL for your email?'
: undefined;
static alphaNumeric = value =>
value && /[^a-zA-Z0-9 ]/i.test(value)
? 'Only alphanumeric characters'
: undefined;
}
Upvotes: 2