JavaScript

  1. Home
  2. Computing & Technology
  3. JavaScript

Email Address Validation

3. Add to Your Page

clr gif

You next attach the script into your web page that has forms containing email addresses by adding the following code into the head section of your page.

<script type="text/javascript" src="email.js">
</script>

All that remains then is to call it using the following statement from either the onblur event of the email field itself and / or the onclick or onsubmit event of the submission button or form:

valid_email =
validateEmail(email_field,mandatory,messages);

The email address to be validated needs to be passed in place of email_field in the above code. If the email field is mandatory then the mandatory field should contain '1' otherwise it should be '0'. The messages field can be set to '1' to return individual messages about which particular test that the email address failed to meet. The error messages will be suppressed if this is set to '0' and you can provide your own failure message. The value returned will be true if the email address is considered to be valid and false if it isn't.

If you prefer you can incorporate the call into an if statement processing the appropriate code based directly on the value returned instead of having to test the valid_email field. For example you could place the following into your validation code to validate a mandatory email field:

if (!validateEmail(emailfield,1,0)) {
alert('email address is invalid or was not entered');
return false;}

This validation routine avoids the use of regular expressions and sticks with the most simple javascript code so that it can validate email addresses in all browsers.

Since writing this script I have been kindly provided with a copy translated into Spanish. I have also been asked how to use the script to validate the To addresses for an email being sent to multiple destinations.

Note that the script and the description of how to use it are copied from the "Ask Felgall" website with the permission of the copyright owner.

Explore JavaScript

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

JavaScript

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.