0

A textbox in a WinForm I have created is for e-mail.
I'm checking the validation of the e-mail format. The string seems to be ignoring the "." condition? According to my test, it runs:

  1. abcdef - Not valid (Correct)
  2. abcdef@gmail - valid (Incorrect)
  3. abcdefgmail.com - Not valid (Correct)
  4. abcdef@gmail.com - Valid (Correct)

Code Snippet:

Regex RX = new Regex("^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
Josh M
  • 173
  • 5
  • 17
  • You need to escape the dot using `\.` – MakePeaceGreatAgain Mar 05 '15 at 14:43
  • 2
    The reason it's "ignoring" the `.` is that that's a wildcard in regex. Escape it as follows: `\.` – David Faber Mar 05 '15 at 14:43
  • 3
    Validating an email-address using regular expressions is a bit more complicated than your implementation here. Your expression will also fail for addresses having dots or hyphens in them, both of which are - among others - valid characters in email addresses. Please see also this question for reference: http://stackoverflow.com/q/201323/1521227 – Spontifixus Mar 05 '15 at 14:44
  • 1
    By the way, there are many valid email addresses that will be rejected by your regex. – David Faber Mar 05 '15 at 14:44
  • Why are you limiting the user-part to 20 and the top-level-domain-part to 3 letters? Thus you reject many many adresses – MakePeaceGreatAgain Mar 05 '15 at 14:46

1 Answers1

1

I think you need to add a backslash in front of the dot:

"^[a-zA-Z0-9]{1,20}@[a-zA-Z0-9]{1,20}\.[a-zA-Z]{2,3}$"

Without that \, . will match any character.

David Faber
  • 12,277
  • 2
  • 29
  • 40
Marco
  • 141
  • 14