9

Possible Duplicate:
Validate email address in Javascript?

I know there is no way to validate an email address by using only regex, but I think I should be able to reject some obviously invalid ones in order to help friendly users who by mistake entered something different, such as their name or password into the email address field. So, I do not want to reject any valid email addresses, but would like to reject as many invalid email formats as is possible using only a regex. But I guess any javascript/jquery/... would be ok too.

Here is what I have so far:

^.+@.+\..+$

Yes, there is no regex for real validation, but there should be some for rejection. No, this will not prevent anyone from entering fake addresses. Yes, you still have to send a confirmation email to validate for real.

The above regex will be used from javascript.

--

In .NET I would instead let .NET validate the email format using

    try
    {
      var mailAddress = new MailAddress(possibleMailAddress);
    }

and if ok, check the DNS records for the domain part to see if there might be an email server. Only if the DNS records clearly indicate that there can be no email server or if there is no such domain then the email address is rejected. Then cache some of the results in order to speed up future lookups.

Still, I have to send confirmation emails for validation...

7
  • 3
    I think you've got a sensible regex here. Although there are addresses without any dots in them, they are probably quite rare. Commented Jul 24, 2012 at 7:11
  • I agree that this is a pretty sensible regex for a public-facing web site. You might also want to consider this answer to the related-but-not-quite-the-same question "Validate email address in Javascript?" Commented Jul 24, 2012 at 7:15
  • Lots of discussion of varying degreees of checking using a regex here: stackoverflow.com/questions/46155/…. Seems like a duplicate question to me.
    – jfriend00
    Commented Jul 24, 2012 at 7:20
  • I think if you want to prevent "false negatives" this is fine: ^[^@]+@[^@\.]+(\.[^@\.]+)*$ or perhaps ^.+?@[^@\.]+(\.[^@\.]+)*$
    – Alvin Wong
    Commented Jul 24, 2012 at 7:20
  • Your current RegEx will probably allow this: test@[email protected]
    – Alvin Wong
    Commented Jul 24, 2012 at 7:24

1 Answer 1

6

The official standard RFC 2822 describes the syntax that valid email addresses with this regular expression:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Not the answer you're looking for? Browse other questions tagged or ask your own question.