Possible Duplicates:
Email Validation – Regular Expression
What is the best regular expression for validating email addresses?
Hi All,
I have an email address roughly like this,
firstname.lastname@4domain.co.nz
Which doesn’t work with the regex I have here for email addresses. It doesn’t seem to like the 4 at the start of the domain.
private const string MatchEmailPattern =
@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
@"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
@"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
@"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
Most other corner cases work well with this regex, all of the below are rejected,
Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@test.com"));
Assert.IsFalse(EmailValidator.IsValidEmailAddress(".a@test.com"));
Assert.IsFalse(EmailValidator.IsValidEmailAddress(".@s.dd"));
Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@988.120.150.10"));
Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@120.256.256.120"));
Assert.IsFalse(EmailValidator.IsValidEmailAddress("2@bde.cc"));
Assert.IsFalse(EmailValidator.IsValidEmailAddress("-@bde.cc"));
Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@bde.cc"));
Assert.IsFalse(EmailValidator.IsValidEmailAddress("_@bde.cc"));
Any other regexes people can suggest for emails that will work with the above?
Also the above regex has the advantage that it works with addresses like this, and a lot of them don’t,
You should use the
MailAddressclass, like this:If you use this approach to validate the e-mail address, be aware, that this
MailAddressaccepts the display name part of the e-mail address as well, and that may be not exactly what you want to achieve. For example, it accepts this strings as valid e-mail addresses:In these cases only the last part of the strings is parsed as the address, the rest before that is the display name. To get a plain e-mail address without any display name, you should check if the
DisplayNameproperty of theMailAddressinstance is empty.Furthermore an address having a dot at the end, like “user@company.” is accepted by MailAddress either.