3

Possible Duplicate:
What is the best regular expression for validating email addresses?

I'm using a form which ask for email address. I used regular expression for it as

.*@.*\..*

But it is not working fine for some of my test email id like

dsrasdf@@@fer@hbdf.vjif

Any one provide me regular expression for the email validation in asp.net or can i use any other method for it.

Please give your suggestions.

Community
  • 1
  • 1
Nagarajan Ganesh
  • 573
  • 1
  • 5
  • 17
  • As a rule of thumb: Think at least twice before using `.` in regular expressions. Note that `....@......` also matches your expression. – Michael Sep 07 '10 at 09:26
  • @Michael: In that particular case it actually makes sense to have a rather loose validation. Actual email addresses follow highly complex rules and it usually is not worth the effort to create an overly complex (read erroneous) regular expression. For example, some major freemail providers don't allow the perfectly valid '+' character. Bam. – Dirk Vollmar Sep 07 '10 at 09:31
  • True, still, using `.` should only be done with caution and is, in this case, still wrong. IMHO, this validation is neither "too loose" nor "too strict" since the strings are neither a superset nor a subset of the real valid email addresses. It's just wrong. – Michael Sep 07 '10 at 09:57

3 Answers3

5

Best to rely on the framework for this kind of stuff.

try {
    address = new MailAddress(address).Address;
} catch(FormatException) {
    //address is invalid
}
Community
  • 1
  • 1
Vinzz
  • 3,968
  • 6
  • 36
  • 51
  • Though I'd say only if you're using .Net 4, I'm fairly sure earlier versions would fail on various types of valid email addresses. – Hans Olsson Sep 07 '10 at 09:37
  • I beg your pardon, but this snippet of code is OK since .NET 2 One has to catch the exception, though. [ http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress.aspx ] – Vinzz Sep 07 '10 at 09:46
1

I am using the following regular expression for my email validations (case insensitive):

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$

I do not know about asp, but i think that you can use it like this.

jwueller
  • 30,582
  • 4
  • 66
  • 70
0
^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z{2-4}|[0-9]{1,3})(\]?)$
Bob
  • 3,074
  • 11
  • 43
  • 62