Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the least bad regex to reject definitely invalid email addresses? [duplicate]

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...

like image 731
tomsv Avatar asked Jul 24 '12 07:07

tomsv


1 Answers

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])+)\])
like image 123
Ωmega Avatar answered Oct 04 '22 03:10

Ωmega