I'm working on validating multiple emails from an input field and can't really get my Regex to work. I have an input field that has emails separated by a comma, semi-colon, space and sometimes no space, something like this:
user1@email.comuser2@gmail.com , user3@email.com;user4@gmail.com user5@email.com
I'm trying to get all emails using Regex and then validate each of them, but not really sure how to do it using Regex in Javascript.
I have written my code in Java and it works great at getting all emails:
Java code:
String employeeEmails = "user1@email.com , user2@gmail.com user3@email.com;user4@gmail.com";
Matcher eachEmail = Pattern.compile("\\w+@\\w+.com").matcher(employeeEmails);
List<String> emailList = new ArrayList<String>();
while (eachEmail.find()){
emailList.add(eachEmail.group());
}
Finally emailList has all the emails
Now I'm trying to get all emails in Javascript and validate each of them and if one of them is not a valid email throw an error. Here's my code:
Javascript:
var regex1 = /\w+@\w+.com/; // This will get all emails from inputField
var emailList = regex1;
var regex2 = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; // This will validate each email
for(var i = 0;i < emailList.length;i++) {
if(!regex2.test(emailList[i])) {
return me.invalidText; // throw error if an email is not valid
}
}
Need to get this done in Javascript. Can anyone tell me what I'm missing please? Thank you in advance!