Web Design / HTML

  1. Home
  2. Computing & Technology
  3. Web Design / HTML

Validate an Email Address in an HTML Form with JavaScript

By Jennifer Kyrnin, About.com

  1. This portion of the script shows how to validate for an email address. It is a very simple validation, it only checks to make sure that there is a @-sign and a period. People can still put in fake email addresses, but this helps reduce the wrong entries a little.
      if (theForm.email.value == "")
      {
        error += "You must include an accurate email address for a response.\n";
      }
      if ((theForm.email.value.indexOf ('@',0) == -1 ||
       theForm.email.value.indexOf ('.',0) == -1) &&
       theForm.email.value != "")
      {
        error += "Please verify that your email address is valid.";
      }
  2. This is the meat of the script. It does two things, first it checks to see if there is an error set. If there is, it displays it as an alert message. Then it sends the return value of false, so that the form information is not sent to the server.

    Your error messages (set in the above if statements), all include a "\n" at the end of the line. This tells the browser to insert a carriage return (or "enter" or "new line") at the end of the line. Then, if there are several error messages they will all be on separate lines.

    If there are no error messages set, then the error variable will be blank (from where we set it at the top of the script), and so the form information will be sent to the server to be acted upon by the CGI.
      if (error != "")
      {
        alert(error);
        return (false);
      } else {
        return (true);
      }
  3. Don't forget to close your script.
    }
    // -->
    </script>

Then, to call the script, put an onsubmit element in the form tag:

<form action="" method="post" onsubmit="return Validator(this);">

See the script in action.

Page 4: Use a Perl CGI script to validate your HTML forms.

Explore Web Design / HTML

About.com Special Features

Web Design / HTML

  1. Home
  2. Computing & Technology
  3. Web Design / HTML
  4. HTML and XHTML
  5. XHTML
  6. Forms
  7. HTML Form Validation - Validating Forms with JavaScript or CGI - Validate an Email Address with JavaScript

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

All rights reserved.