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

Yehuda Shiran, Ph.D.
Doc JavaScript

WebDev News
Sun to Simplify Java
FreeBSD 5.0 Unleashed
UnitedLinux Targets Telecommunications Carriers
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.


People who read this tip also read these tips:

Look for similar tips by subject:

Copyright 2003 Jupitermedia Corporation All Rights Reserved.
Legal Notices,  Licensing, Reprints, & Permissions,  Privacy Policy.
http://www.internet.com/
webref The latest from WebReference.com Browse >
Event Logging in .NET · Book Excerpt: Speed Up Your Site, Pt. 2 · Book Excerpt: HTTP: The Definitive Guide
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Supreme Court Decision Spurs Debate · Identifying Identity Theft · Standardizing Network Management Procedures