0

Possible Duplicate:
Using a regular expression to validate an email address

I have a regular expression for validating email addresses. It works pretty well, but it doesn't pick up if I've added any characters at the end. For example, if I try.... "eee" it will flag it as invalid, If I try "ddd@dddd.com" that passes, but if I try "dfdfd@Dfdf.comd" it also passes. Is there anything to stop these invalid characters being picked up at the end?

Here is my regex:

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

Thanks

Community
  • 1
  • 1
Funky
  • 12,890
  • 35
  • 106
  • 161
  • This question has been asked an enormous number of times on SO - please use the search function, e.g. [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – RB. Sep 13 '12 at 08:58

2 Answers2

1

You can check for common endings with a list such as (com|uk|org|gov) but there are so many variations that checking them all isn't suited to regex. Either you pull out the top-level domain and check it against a list, or you trust your users.

deadly
  • 1,194
  • 14
  • 24
  • There are going to be a lot more variations soon, as ICANN is allowing people to create their own [top-level domains](http://newgtlds.icann.org/en/) :) – RB. Sep 13 '12 at 09:06
  • Yeah, like I said, this isn't really suited to regex. – deadly Sep 13 '12 at 09:07
0

Well, your pattern would have to know about all valid suffixes.

A regex for validating standard compliant eMail addresses is in fact quite complex. Check out http://www.regular-expressions.info/email.html for some pointers on how to achieve this.

"Short" answer (taken from the above link, didn't test it, you might have to adapt it to your regex implementation):

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b

As you can see, that pattern also does some sort of whitelisting for the valid suffixes.

EDIT: Or just check out this answer, good explanation and a reference to the official standard regex (it seems): Using a regular expression to validate an email address

Community
  • 1
  • 1
DeX3
  • 5,200
  • 6
  • 44
  • 68