0

Possible Duplicate:
Using a regular expression to validate an email address
Email Validation - Regular Expression

I use the below regular expression to validate an email address. But we found out that "*" or "/" are accepted by this regular expression but it's shouldn't!

Regex.IsMatch(email, 
   @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
   @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
   RegexOptions.IgnoreCase, 
   TimeSpan.FromMilliseconds(250));

Please I need your help in improving the RE to not allow "*" or "/" FYI the above code is in C#

Community
  • 1
  • 1
user1904221
  • 41
  • 1
  • 4

1 Answers1

1

You need a big fix..

If you want to validate an Email Address Regex is not the right choice.

Use MailAddress as recommended by SLaks

try 
{
   address = new MailAddress(address).Address;
   //address is valid here
} 
catch(FormatException) 
{
   //address is invalid
}

But if you are addicted to regex..just do this

.*@.*
Community
  • 1
  • 1
Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • I'm not sure that a catch block is the right place to handle invalid user input. Is that enforced by the library or does it expose some validation property that you can check before accessing the address? – Ant P Jan 26 '13 at 10:32
  • @AntP `MailAddress`'s **Address** property throws `formatexception` if the address is **invalid**..if the exception is thrown you would know that the email is invalid. – Anirudha Jan 26 '13 at 11:10
  • I realise that but I would not consider validation of an email address' format to be **exceptional** program flow and hence question whether exception handling is the correct way to deal with an invalid email address (assuming the email address comes from some user input as opposed to, say, a config file). – Ant P Jan 26 '13 at 11:16
  • @AntP yup it is..atleast it guarantees to validate anykind of emailid's..there are various corner cases wherein a regex would fail – Anirudha Jan 26 '13 at 11:18
  • You're still missing the point. **Exceptions** are designed for **exceptional** behaviour - when the application behaves in a way that is **outside of the expected program flow**. User input validation does not meet these criteria, so using exception handling to validate email addresses in this way is messy and - if we're being pedantic - adds unnecessary overhead. I'm not saying it won't work, I'm saying that it doesn't seem like a very tidy approach. – Ant P Jan 26 '13 at 12:59