4

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

I tried the reg expression

^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+

for the email validation.

Since I want the user to allow submitting even with the empty email address. So I changed the reg ex to

(^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+)?

But this expression accepts any email address without any validation.

Community
  • 1
  • 1
Mohammad Nadeem
  • 9,134
  • 14
  • 56
  • 82
  • 1
    Your expression will accept anything because it can match the empty string (the ? meaning zero or one times) and every string "contains" the matching string. You want to compare the whole string, so put ^at the beginning and $ at the end - this way nothing BUT your regex can occur in the string. So either it is empty OR the complete pattern. – Konerak May 25 '10 at 13:07

4 Answers4

3

Thanks Konerak!!!! I changed the expression to

^(([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+)?$

and this is working for me.

Mohammad Nadeem
  • 9,134
  • 14
  • 56
  • 82
1

Welcome. http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

miku
  • 181,842
  • 47
  • 306
  • 310
  • I think this is unrealistic because RFC822 includes a lot of legacy address types that are rarely needed or supported by current software. – kervin May 25 '10 at 13:13
  • yeah, this is not practical. far better is this, and the discussion around it: http://www.regular-expressions.info/email.html – Richard H May 25 '10 at 14:17
1

A good bit of info on doing this is available at this page.

As that page will tell you, it's extremely difficult to pass any and all RFC822-compliant addresses with a regex. You need to ask yourself just how important this is to your application.

Personally I would recommend, if applicable, simply asking users to enter the email address twice and then confirm with a confirmation email. That way you don't run the risk of erroneously rejecting a valid email address (an extremely annoying situation for users which will likely lose your site some customers).

Steven Mackenzie
  • 386
  • 3
  • 10
1

How to: Verify That Strings Are in Valid E-Mail Format

volody
  • 6,946
  • 3
  • 42
  • 54