September 28, 1999 - Is That Really an Email Address? | WebReference

September 28, 1999 - Is That Really an Email Address?

Yehuda Shiran September 28, 1999
Is That Really an Email Address?
Tips: September 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

If you've got a form that requires the user's email address, you should apply client side validation. Although we won't discuss form processing in this tip, we'll show you how to check if a given string represents a valid email address. The following function accepts a string and returns a Boolean value:

function isEmail(str) {
  // are regular expressions supported?
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported) 
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}

Simply hand a string to the function, and it'll tell you if you've got a valid email address (it checks the syntax, not the actual existence of the address). Note that this function works with all JavaScript-enabled browsers, but provides a more advanced algorithm for fourth-generation browsers (Navigator 4.0x, Internet Explorer 4.0x, and above).

For more information on regular expressions, and how to use them to verify an email address, read Column 5, Regular Expressions.