0

I am working to validate a string of email addresses. This pattern works fine if there is only one email address:

var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

But if I have two email addresses separated by space or by a newline, then it does not validate. For example:

xyz@abc.com xyz@bbc.com

or

xyz@abc.com 
xyz@bbc.com

Can you please tell me what would be a way to do it? I am new to regular expressions.

Help much appreciated! Thanks.

dda
  • 6,030
  • 2
  • 25
  • 34
Shah
  • 4,878
  • 8
  • 25
  • 33

6 Answers6

2

Try this RegEx

/^\s*(?:\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}\b\s*)+$/

Regular expression image

In the above image, everything inside Group 1 is what you already had. I have added a word ending and spaces.

It will match "xyz@abc.com", " xyz@bbc.com ", "xyz@abc.com xyz@bbc.com" and email addresses in multiple lines also.

Update

I got the RegEx for Email from http://www.regular-expressions.info/email.html and I have used it in my expression. You can find it below:

/^\s*(?:([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b\s*)+$/i

Regular expression image

Community
  • 1
  • 1
ManojRK
  • 952
  • 9
  • 22
1

Change the ^ and $ anchors to word boundaries, \b.

/\b\w+...{2,3}\b/

You should also note that the actual specification for email addresses is extremely complicated and there are many emails that will fail this test -- for example those with multiple periods in the domain. May be okay for your purposes, but just pointing it out.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

try this

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;
}
Mathi
  • 742
  • 1
  • 10
  • 15
0

You might consider simply splitting the whole string into an actual array of email addresses, instead of trying to validate the entire thing at once. This has the advantage of allowing you to point out in your validation message which address failed. uld look like this:

  var emailRegex = /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i; // http://www.regular-expressions.info/email.html
  var split = form.emails.value.split(/[\s;,]+/); // split on any combination of whitespace, comma, or semi-colon

  for(i in split)
  {
     email = split[i];
     if(!emailRegex.test(email))
     {
          errMsg += "The to e-mail address ("+email+") is invalid.\n";           
     }
  }
Jake Toronto
  • 3,524
  • 2
  • 23
  • 27
0

Your best regular expression for multiple emails accepts all special characters

(-*/+;.,<>}{[]||+_!@#$%^&*())

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
Aryan
  • 1
  • 4
-2

Best Regular Expression for multiple emails

/^([A-Z0-9.%+-]+@[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+@[A-Z0-9.-]+.[A-Z]{2,6}))*$/i