I need a tested method of email validation in javascript

There are literally thousands of postings out in the big wide web for email validations and the best I have seen usually use regular expressions. I don't know how to write my own regexp but I do understand them in a way. Here is my dilemma.

No matter what function I find to validate an email address, there are always replies from others that prove that the function is not correct because it does not allow for certain "VALID" email formats. This is driving me nuts. What are the rules for validating email addresses?

Surely, someone out there has gone through ALL of the email rules for what is valid and what is definitely NOT valid. I need a javascript function that is 100 percent rock solid and returns false if an email is not valid and true if valid. It should be widely excepted by other experts. Is there such a function out there? I'm sure there is but I just can't keep reading to find one as like I said, someone always kicks them back and proves that it does not work.

I just want to have a simple function that works 100% of the time. Please help me by supplying me with a jscript function that is commercially correct and works. Thanks in advance.
By the way, this question has been asked a gazillion times on EE with the same results (others commenting that is does not work 100%). What do commercial companies use? Does anyone know ALL the rules and have made a reg expression that covers them all?

My form is not a real form. It is only a text input filed and I process it with javascript and use ajax to send the form field values to a php script for processing so I don't need a function that will submit a form or anything. A function to return true or false would be perfect. So I can use like this

function validateEmail(email){
// the function goes here.....
}

To use:

if(validateEmail(email)){
// continue with form validation and send to php script
} else {
// email not valid
alert('Please enter a valid email address!');
document.getElementById('email').focus();
exit;
}
LVL 20
Mark BradyPrincipal Data EngineerAsked:
Who is Participating?
 
nap0leonCommented:
I used this function to verify the email address is valid while working at a Fortune 100 company with no complaints what-so-ever:
function isValidEmailFormat(strEmail){
    var isemail = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
    if (isemail.test(strEmail)){
        return true;
    } else {
        return false;
    }
}

Open in new window


Does it handle all cases?  Of course not... there are too many custom rules.  What it does do though is handle 98% of all valid emails.  People with wacky email addresses will surely have experienced issues with their email address on other sites as well.

If you are concerned with pissing off a client who insists that his email is valid, they always have the option of using a common-format email address.  It is there choice to use the wacky email format and must suffer the consequences of their choices.

If you want to truely validate the email address... there are paid solutions where you can use an AJAX call to a 3rd party company that "pings" the email address to see if it is valid.  Like, if someone entered elvin.66@yahoo.com, the service would ask yahoo.com if the email address was valid or not.  Depending on how much you want to pay you can get back a simple "yes or no" as to whether the email server exists (is yahoo.com a valid email server) or you can find out if the email address itself is actually correct (this would capture errors in case the user had a typo in their email address, perhaps entering elvin66@yahoo.com instead of elvin.66@yahoo.com)
0
 
mandriluyCommented:
function validateEmail(email) {      
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;     return re.test(email);
}  

Open in new window


Please remember that you also have to validate your field serverside, JS is very easy to hack/disable and is not a real validation system.
0
 
leakim971PluritechnicianCommented:
>What do commercial companies use?

client side script (javascript or others) should not be used to really validate an email, use a server side language
the best is to send an email and wait user validation (he should receive it)

Else...
This following regex come from the jQuery validate plugin : http://jsfiddle.net/VxkY2/1/

function validateEmail(email) {
// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(email)
}

Open in new window


if you want to validate the TLD : http://jsfiddle.net/VxkY2

ressources : http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains

function validateEmail(email) {
    var tld = email.split(".").pop();
    var tlds = ["com","biz","fr","and so on"]; // add TLDs here!!!
    for(var i=0;i<tlds.length;i++) if(tlds[i]==tld) return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(email);
    return false;
}

alert(validateEmail("bad@bad")); 
alert(validateEmail("bad@bad.bad"));
alert(validateEmail("bad@bad.fr")); // good

Open in new window

0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
käµfm³d 👽Commented:
This might be an interesting read for you:  http://www.regular-expressions.info/email.html

The author gives his opinion on why you don't see a very specific regex for emails; however, he does provide you with a regex that follows the RFC pertaining to email addresses (be sure to scroll all the way to the right to grab the whole regex!).
0
 
Mark BradyPrincipal Data EngineerAuthor Commented:
Thanks for all the quick replies. I read the article 'kaufmed' posted and that is interesting but backs up what I was saying about the rules. I would like to believe that there are exact rules that must be followed so there would be a regex somewhere that follows those rules. But it seems that this is not the case. There is always something that will break those rules and still be valid.

I am not writing a top secret government application, just a simple online booking system so I don't need absolute precision to the enth degree but was hoping to get a well used and widely excepted method of doing client side validation, then once I get to the serside, do an additional validation there as well.

As this question is only regarding the client side (javascript) validation, I won't ask for a serverside solution as well but I am confused over which of the above answers will be the best one to use for my client side. I don't mind splitting the points as I'm sure all of your answers will work, however I need help in deciding which one will work best for me.

If it helps, the majority if not ALL email addresses that will be entered into my form will come from users in New Zealand, or users in the USA so I don't need to worry about russian domains names or middle east domains etc.. As we have a lot of immigrants in New Zealand and the same goes for the USA I do need it to be able to identify most western countries like .co.uk for example.

I don't want to drag this out so need a nudge in the right direction. Thanks again to all who responded.
0
 
käµfm³d 👽Commented:
I would like to believe that there are exact rules that must be followed so there would be a regex somewhere that follows those rules.
The "official" word on things like this is typically the RFC. The problem is, as it is in any software system, that anyone can either interpret the RFC as they see fit, or decide to not follow the RFC at all. It's the same with compilers. Sure, there are standardized compilers which follow the C99 standard, but there are also compilers which do not follow the standard and allow certain "tricks" that other compilers do not.

In the case of email, the only sure method of validation is to try and send the email. Barring that, you have to decide what you are going allow for variance.
0
 
StingRaYCommented:
Why do not you use something like activation by email. Once user registered to you site, send him an email to activate his account. If he clicks the link given in the email, the account becomes active. Otherwise, it will not be usable.

In the booking system, you do not need further email validation. You already validated by user response.

Does this make sense to you?
0
 
käµfm³d 👽Commented:
Ah, StingRaY beat me to it. I was just about to say I think this is why many sites now send out a confirmation email that users must subsequently click the link within the email in order to activate their account. If they don't click the link before the timer expires, the account registration is deleted, and the user must re-register.
0
 
Mark BradyPrincipal Data EngineerAuthor Commented:
Yes StingRay, I already send out a validation email to confirm their booking. If they confirm by clickming a link in the email then their booking is advanced in status to "complete" and the company receives an email notifying them of the apoinment. This was always my intention. The problem is, my client (who I wrote this app for) does not like the fact that he can book with anything in the email field, even though he will never get a validation email cause the address does not exist. He wants to see an alert on the clientside if the address is not valid in format (no need to test for real domain). I have put email validation including domain verification in my php script that receives the submitted form (via ajax) and that works well.

The client just wants some further warnings if they enter a bum address. Personally I don't think it is required because of the serverside verification but you can't argue with the one who will pay your bill if you do as they ask :)

Perhaps I just need a simple, basic validation regex to filter out obvious mistakes and typos in javascript. If I could get a basic regex to use I would be happy with that (even though the question calls for exact tested code). I changed my mind and will run with basic checking.

After reading all the comments I can see the logic a bit clearer now.
0
 
StingRaYCommented:
I understand your situation.

Back to the validation. You may know the email address syntax. If not check this link (http://en.wikipedia.org/wiki/Email_address). You can see the weird addresses there.

much."more\ unusual"@example.com
very.unusual."@".unusual.com@example.com
very."(),:;<>[]".VERY."very\\\ \@\"very".unusual@strange.example.com

Are they still to your payer?

In my opinion, the client side validate is only coarse validation while the validation I mentioned above is a fine validation.
0
 
Mark BradyPrincipal Data EngineerAuthor Commented:
ok thanks StingRay. After reading those rules, can you give me a basic regexp to check for the '@' and the '.' and that it doesn't end in a '.' period or start with a '.' period. I think that will cover the javascript side.
This is the new php function I am trying to use but so far it is causing a server error so something must be screwy somewhere...

function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") ||
 ¿checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}
0
 
Mark BradyPrincipal Data EngineerAuthor Commented:
Thanks for that explanation. I agree, I'm not worried about rejecting the few who choose to use out of the norm email formats. Like I said, my app is just a booking system for a company so it does not need to be fireproof and I do have a pretty good back end php check that I did get working. I just needed a simple front end script to trap the obvious mistakes either by typos or outright mistakes in email addys. The only advantage to using both client and serverside checks is that if I catch it on the client side I can save load on the server as I can halt the javascript and send them back to fix up the email instead of making the server call and waiting for a response. Just speeds things up a little.

Your function will work just fine. Thanks to everyone for your comments and replies.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.