Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a comma separated list of emails with regex?

Tags:

c#

regex

asp.net

Trying to validate a comma-separated email list in the textbox with asp:RegularExpressionValidator, see below:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
                    runat="server" ErrorMessage="Wrong email format (separate multiple email by comma [,])" ControlToValidate="txtEscalationEmail"
                    Display="Dynamic" ValidationExpression="([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},?)" ValidationGroup="vgEscalation"></asp:RegularExpressionValidator>

It works just fine when I test it at http://regexhero.net/tester/, but it doesn't work on my page.

Here's my sample input:

[email protected],[email protected]

I've tried a suggestion in this post, but couldn't get it to work.

p.s. I don't want a discussion on proper email validation

like image 451
roman m Avatar asked Dec 10 '10 19:12

roman m


People also ask

How does regex match email format?

[a-zA-Z0-9+_. -] matches one character from the English alphabet (both cases), digits, “+”, “_”, “.” and, “-” before the @ symbol. + indicates the repetition of the above-mentioned set of characters one or more times.

Can you use a comma in an email address?

A common usage is for defining sub-addresses. Example: The user 'joe' with the mail address '[email protected]' can set up mail addresses like '[email protected]' if he needs more then one address. The comma is used in address header fields to separate email addresses from each other.


2 Answers

This Regex will allow emails with spaces after the commas.

^[\W]*([\w+\-.%]+@[\w\-.]+\.[A-Za-z]{2,4}[\W]*,{1}[\W]*)*([\w+\-.%]+@[\w\-.]+\.[A-Za-z]{2,4})[\W]*$

Playing around with this, a colleague came up with this RegEx that's more accurate. The above answer seems to let through an email address list where the first element is not an email address. Here's the update which also allows spaces after the commas.

like image 164
Matt Avatar answered Sep 20 '22 17:09

Matt


Try this:

^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},?)+$

Adding the + after the parentheses means that the preceding group can be present 1 or more times.

Adding the ^ and $ means that anything between the start of the string and the start of the match (or the end of the match and the end of the string) causes the validation to fail.

like image 44
Donut Avatar answered Sep 20 '22 17:09

Donut