Ask the JavaScript Pro 10-Minute Solutions

Verify the Format of an E-Mail Address Entry
By Boris Feldman

One of the most popular fields on Web forms is the e-mail address field. It would be great if you could confirm that the addresses users enter into your forms are valid. Unfortunately, due to the way Internet e-mail works, this isn't possible. However, using JavaScript, you can check to see whether an e-mail address is in the right format. To accomplish this task, you can use a self-contained function called checkEmail(). This function accepts one parameter: the e-mail address to verify. The function returns true if the address is in the standard format and false if it isn't.

Getting this functionality into your pages is easy. On one hand, you can use the checkEmail() function directly within your own code, and then react accordingly. Otherwise, if don't want to write any code, you can use the wrapper function emailOK() to call checkEmail() for you and display a message if the address provided fails the check.

First, copy the JavaScript code from the sample to your page (see Listing 1). Then modify your form to call either the checkEmail() or emailOK() function. You can either check the e-mail when the user submits the form or when the contents of the field changes.


<INPUT TYPE="TEXT" NAME="email" SIZE="35" 
onChange="emailOK(this.value)">

To see how the code works, let's walk though it. To start with, try to find the @ character within the e-mail address. If you don't find it, return an error.


// check for @
i = emailAddr.indexOf("@");
if (i == -1) {
    return false;
}

Then separate the e-mail address into its username and domain name parts.


// separate the user name and domain
var username = emailAddr.substring(0, i);
var domain = emailAddr.substring(i + 1, emailAddr.length);

Next, remove any spaces from the beginning of the username and the end of the domain name.


// look for spaces at the beginning of the username
i = 0;
while ((username.substring(i, i + 1) == " ") && 
(i < username.length)) {
	i++;
}
// remove any found
if (i > 0) {
	username = username.substring(i, username.length);
}

// look for spaces at the end of the domain
i = domain.length - 1;
while ((domain.substring(i, i + 1) == " ") && (i >= 0)) {
	i--;
}
// remove any found
if (i < (domain.length - 1)) {
	domain = domain.substring(0, i + 1);
}

Now, walk through both the username and the domain name to look for any characters that aren't allowed in e-mail addresses. Convert each character to lowercase and check it. If you find anything that isn't a letter between "a" to "z", a number between "0" and "9", an underscore ("_"), a dash ("-"), or a period (".") then you know the address you're checking isn't good.


// check for bad characters in the username
var ch;
for (i = 0; i < username.length; i++) {
    ch = (username.substring(i, i + 1)).toLowerCase();
    if (!(((ch >= "a") && (ch <= "z")) || 
        ((ch >= "0") && (ch <= "9")) ||
        (ch == "_") || (ch == "-") || (ch == "."))) {
            return false;
    }
}

// check for bad characters in the domain
for (i = 0; i < domain.length; i++) {
    ch = (domain.substring(i, i + 1)).toLowerCase();
    if (!(((ch >= "a") && (ch <= "z")) || 
        ((ch >= "0") && (ch <= "9")) ||
        (ch == "_") || (ch == "-") || (ch == "."))) {
            return false;
    }
}

Finally, check the end of the domain name to make sure that it ends in a valid suffix. This can either be one of the top-level domains or a domain country code.


var bFoundSuffix = false;
i = 0;
while (i < aSuffix.length) {
    if (("." + aSuffix[i]) == domain.substring(domain.length 
- aSuffix[i].length - 1, domain.length)) {
        return true;
    }
    i++;
}

You can find more information about domain name suffixes at:
www.microsoft.com/insider/ie5/tips/domain.htm

That's all you need to do to check e-mail addresses on your forms. Remember, just because an address passes the test doesn't mean it's valid—just that it is in the proper format.


UPDATE: Reader James O'Brian pointed out that this original e-mail verification script does not allow the character '+', which should be valid in an e-mail address.

Our new Pro, Dori Smith suggests checking out http://public.yahoo.com/~jfriedl/regex/email-opt.pl to get a more complete picture; however, it's in Perl.

 
Other 10-Minute Solutions
 Get a Nifty Dropdown Menu Effect
 Create a Text-based Toolbar With a Cool Roll-over Effect
 Create a Drop-down List that Takes Users to URLs
 Fill a Select List With JavaScript
 Implement Cross-Platform Tooltips
 Easily Move Items Between <SELECT> Lists
 Validate the Credit Card Field on Your E-Commerce Site
 Give Your Users Form-Field Feedback
 Speak to Your International Users
 Determine Time Using JavaScript's Date Object
 Verify the Format of an E-Mail Address Entry
 Create a Web-Based Slideshow
 Display a Rotating Text Billboard on Your Site
 Dynamically Access Form Elements With Eval()
 Creating a Countdown
 Calling A Rose by Any Other Name
 A Vacation Slide Show
 Create Fast, Smooth Multi-page Forms with JavaScript


Ask the JavaScript Pro | Who is the Pro? | Usage Policies | Ask a Question | Search | Feedback


Sponsored Links


Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map
Jupiterweb networks

internet.comearthweb.comDevx.comClickZ

Search Jupiterweb:

Jupitermedia Corporation has four divisions:
JupiterWeb, JupiterResearch, JupiterEvents, and JupiterImages

Copyright 2004 Jupitermedia Corporation All Rights Reserved.
Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Jupitermedia Corporate Info | Newsletters | Tech Jobs | E-mail Offers