Regex validation email (certain symbols should be removed) [duplicate]
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
Solution 1:
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.
Solution 2:
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.
Solution 3:
The first answer which is selected as best matches the string like [email protected]@abc.com
which is invalid.
The following regex will work for comma separated email ids awesomely.
^([\w+-.%]+@[\w.-]+\.[A-Za-z]{2,4})(,[\w+-.%]+@[\w.-]+\.[A-Za-z]{2,4})*$
It will match single emailId, comma separated emailId but not if comma is missed.
First group will match string of single emailId. Second group is optionally required by '*' token i.e. either 0 or more number of such group but ',' is required to be at the beginning of such emailId which makes comma separated emailId to match to the above regex.