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?
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(/,|;/)
Use var result = value.split(",")
. You end up with an array.
Regex:
((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,])*)*
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With