Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Multiple Emails Comma Separated with javascript

I want to validate a string which can be an email or multiple emails separated by commas.

For example:

[email protected] -> TRUE
bill -> FALSE
[email protected],[email protected]" -> TRUE
[email protected],[email protected], bob" -> false
bob,[email protected],[email protected]" -> false

I came out with the next code which works with the test cases.

function validateEmail(field) {
    var regex=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
    return (regex.test(field)) ? true : false;
}

function validateMultipleEmailsCommaSeparated(value) {
    var result = value.split(",");
    for(var i = 0;i < result.length;i++)
    if(!validateEmail(result[i])) 
            return false;           
    return true;
}

Is this the quickest way to do it? What if I want to allow ; and , as separator?

like image 598
Sergio del Amo Avatar asked Feb 19 '09 17:02

Sergio del Amo


4 Answers

You shouldn't match top-level domains with [A-Z]{2,4}:

What about .museum or .travel? What about IDNA domains like .xn--0zwm56d or .xn--11b5bs3a9aj6g?

Also, it's perfectly valid to have an email-address like "John Doe"@example.org.

In my opinion, all you should check on the client side is if the address contains an @ and if there's at least one . after it. On the server side, you could check if the server exists (you might even want to try connecting to the appropriate SMTP port) or just send out a validation mail.

Everything else is prone to errors as the actual regex to check for valid email addresses looks like this.


Also, this

return (regex.test(field)) ? true : false;

is a serious WTF - test() already returns a boolean value!


If you want to allow different separators, use a regular expression instead of a string for splitting, eg

value.split(/,|;/)
like image 128
Christoph Avatar answered Nov 09 '22 12:11

Christoph


Use var result = value.split(","). You end up with an array.

like image 39
Diodeus - James MacFarlane Avatar answered Nov 09 '22 13:11

Diodeus - James MacFarlane


Regex:

((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,])*)*
like image 2
Prakash Avatar answered Nov 09 '22 14:11

Prakash


In general it is not possible to validate email addresses. Something that is syntactically valid does not necessarily go anywhere, and even if it does whether it will be read.

And even then, covering all the possible syntactically correct addresses (according to the applicable RFC) needs an extremely complex regex (see 1st edition of "Mastering Regular Expressions" (Friedl, O'Reilly) for the 4724 or 6598 character versions, and these probably don't handle IDNs). E.g. an apostrophe is a valid character in the local part, and you can have comments inside the email.

like image 1
Richard Avatar answered Nov 09 '22 14:11

Richard