I\'m trying to come up with a regular expression to validate a comma separated email list.
I would like to validate the complete list in the first place, then split
Also note that you'll want to get rid of extra spaces so an extra step needs to be added as follows:
var emailStr = "felipe@google.com , felipe2@google.com, emanuel@google.com\n";
function validateEmailList(raw){
var emails = raw.split(',')
var valid = true;
var regex = /^(([^<>()[\]\\.,;:\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,}))$/;
for (var i = 0; i < emails.length; i++) {
if( emails[i] === "" || !regex.test(emails[i].replace(/\s/g, ""))){
valid = false;
}
}
return valid;
}
console.log(validateEmailList(emailStr))
By adding .replace(/\s/g, "") you make sure all spaces including new lines and tabs are removed. the outcome of the sample is true as we are getting rid of all spaces.