Javascript multiple email regexp validation
Solution 1
Split the emails on a comma and validate the entries
var x = getEmails();
var emails = x.split(",");
emails.forEach(function (email) {
validate(email.trim());
});
Where getEmails() gets the emails from the page, and validate runs your regex against the emails
Solution 2
try this
function validateEmails(string) {
var regex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var result = string.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!regex.test(result[i])) {
return false;
}
}
return true;
}
accept both comma and semicolon as separator
Solution 3
Here is a regex for multiple mail validation without split
function validateMultipleEmails(string) {
var regex = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-\.]+)+([;]([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-\.]+))*$/;
return regex.test(string);
}
https://regex101.com/r/TUXLED/1
Solution 4
You should be able to split the entry by commas, and then test the individual email subentries against the regexp.
var valid = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var entries = entry.split(",");
if(valid.test(entries[0]))... //or however your testing against the regex
You might also want to trim any whitespace before testing any of the stripped email substrings.
![Jorge](https://i.stack.imgur.com/MxdJD.png?s=256&g=1)
Jorge
Updated on March 21, 2020Comments
-
Jorge over 4 years
Normally validation of simple email is:
/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
This will validate email like
[email protected]
But how to validate if email is multiple?
entry 1: [email protected], [email protected], [email protected] entry 2: [email protected] , [email protected] , [email protected] entry 3: [email protected], [email protected] , [email protected] entry 4: [email protected]
This emails is a possible entries that user will input. Also expect thier is 2 or 3 or 4 or more emails sometimes.
Thanks for the answers.