JavaScript function to check an email address conforms to RFC822

A number of times I have been frustrated with simplistic verification of email addresses, not so much because they are incomplete, but because they actually get it wrong.

I did at one stage make a serious attempt understanding and implementing the perl regular expression for checking emails (in accordance with the internet specification RFC822) that is found in the Perl Cookbook, however after reading Cal Henderson's excellent write-up on Parsing Email Adresses in PHP, I realise why it wasn't a helpful place to start (it incorporates more than just the address spec).

So with Cal's advice there is no excuse for web developers to continue to guess at what an email address should be, just do it to the spec (RFC822)!

The original is in PHP, and others have rewritten it for Ruby, and Python...

Here is my contribution, a JavaScript version:

(Licensed under a Creative Commons Attribution-ShareAlike 2.5 License, or the GPL)

function isRFC822ValidEmail(sEmail) {

  var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  var sQuotedPair = '\\x5c[\\x00-\\x7f]';
  var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
  var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
  var sDomain_ref = sAtom;
  var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
  var sWord = '(' + sAtom + '|' + sQuotedString + ')';
  var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
  var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
  var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
  var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
  
  var reValidEmail = new RegExp(sValidEmail);
  
  if (reValidEmail.test(sEmail)) {
    return true;
  }
  
  return false;
}

Download the attached JavaScript file, which also has a basic example.

Hope somebody finds this useful.

AttachmentSize
Plain text icon rfc822validemail.js.txt3.42 KB