I want to validate a string which can be an email or multiple emails separated by commas.
For example:
bill.gates@hotmail.com -> TRUE
bill -> FALSE
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(/,|;/)
used this for php preg_match_all()
$pattern = '/([\w+\._%-]+@[\w+\.-]+\.[\w+]{2,4}[^,;\s])/';
$text = 'abc@efg.com, efg, hij@emg.com, ak@efg asfbd@efg.com ab@sdfs.com abc+efg@pqr.com';
preg_match_all($pattern, $text, $match);
var_dump($match);
array(2) {
[0] =>
array(5) {
[0] =>
string(11) "abc@efg.com"
[1] =>
string(11) "hij@emg.com"
[2] =>
string(13) "asfbd@efg.com"
[3] =>
string(11) "ab@sdfs.com"
[4] =>
string(15) "abc+efg@pqr.com"
}
[1] =>
array(5) {
[0] =>
string(11) "abc@efg.com"
[1] =>
string(11) "hij@emg.com"
[2] =>
string(13) "asfbd@efg.com"
[3] =>
string(11) "ab@sdfs.com"
[4] =>
string(15) "abc+efg@pqr.com"
}
}
How about splitting the string into an array and looping through it passing just one e-mail address at a time?
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;
}
accepts both comma and semicolon as separator, change that if you want only comma as separator
I would throw an $.trim(result[i])
into that validateMultipleEmailsCommaSeparated
function as many people will add the space after their comma.
Of course that is a jQuery thing so do the equivalent your way.
Regex:
((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,])*)*