1

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!

Devmix
  • 1,599
  • 5
  • 36
  • 73

1 Answers1

0

I hope this help you:

employeeEmails = "user1@email.com , user2@gmail.com user3@email.com;user4@gmail.com*john@doe";

function extractEmails(x) { return x.match(/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/g); }

var emails=extractEmails(employeeEmails);

    //  The emails already in an array, now a more exhaustive checking:

function validateEmail(v) { 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,}))$/;
    return regex.test(v);
}

emails.forEach(function(email, index)
{   
    //  Here you can handle each employee emails.
    //
    //  Example:
    var verified=validateEmail(email);
    document.write(' validation is '+ verified +' for '+ email +'<br>');    
});

Sources: