Javascript multiple email regexp validation

22,781

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.

Share:
22,781
Jorge
Author by

Jorge

Updated on March 21, 2020

Comments