Validating Forms With JavaScript & HTML 5

Many webmasters' first experience with website design techniques beyond pure HTML is using JavaScript to validate form data - most often, mail forms which are a common source of SPAM. This tutorial demonstrates how you can use easily JavaScript to effectively validate a user's entries in all of your online forms, with special emphasis on contact/email forms and the new capabilities of HTML 5.


Form validation generally consists of three tasks: (1) insuring that the user completed an entry in all required fields; (2) checking that all of the entries are appropriate for the type of information being gathered; and (3) handling the situation when the user submits invalid form data. The first task is very simple because all that it requires is checking to see that the form field is not empty - the user entered something, no matter what that may be.

Here's a good example of a contact form that you might see on any website:







The HTML mark-up for this form is shown below:

<form method="post" action="example.php" id="myform" onsubmit="return rdValidateForm(this);">
<label for="name">Name:</label>
<input name="name" type="text" size="40" placeholder="Your Name" required><br>
<label for="company">Company:</label>
<input name="company" type="text" size="40" placeholder="Company Name" required><br>
<label for="email">Company Email:</label>
<input name="email" type="email" size="40" placeholder="you@yourcompany.com" required><br>
<label for="phone">Phone:</label>
<input name="phone" type="text" size="20" placeholder="Daytime Phone" required><br>
<input type="submit" value="Submit"><br>
</form>

I made sure to take advantage of several features of HTML 5, particularly the 'placeholder' attribute which shows a hint to the user in the text boxes about what information should be entered. I also used a couple of new HTML 5 options for the 'type' attribute which, in conjuction with the 'required' attribute, lets modern browsers have the first chance to validate the user's entries with visual clues that appear when the user presses the "Submit" button. As with most HTML 5 features, older browsers treat them as standard 'text' inputs, so there's no compatibility issues - just less convenience. But even with all of the help that HTML 5 brings, we still need some JavaScript to insure that the user has filled in the form properly.

My JavaScript validation function is called by adding an 'onsubmit' attribute to the <form> tag, using 'return rdValidateForm(this)'. There are two important aspects to the JavaScript code contained in the attribute value. First, note the use of the keyword 'return', which means that the result of the validation function will be passed back to the browser's form handler. A result of 'true' means that the browser should complete the submission process using the values in the 'action' and 'method' attributes. A result of 'false' means that the submission process should be stopped, which allows the user to immediately make changes to his entries. The code is shown below:


var rdFieldNames = {"name":"Name", "company":"Company", "email":"Company Email", "phone":"Phone"};
var rdFieldTypes = {"name":"alpha", "company":"alpha", "email":"email", "phone":"phone"};

 function rdValidateForm(theForm) {
  var badFields = new Array()
  var valid = true;
  var min_alpha_length = 4;
  var min_numeric_length = 4;
  var numeric_reg_exp = /^\d+$/i;
  var us_phone_reg_exp = /^(\d{3})?(\d{7})$/i;
  var EMail_reg_exp = /^[a-z][\w\.\-]*@[\w\.\-]+\.[a-z]{2,}/i;
  var err = "There is a problem with your entries:\n\n";
  for (var key in rdFieldNames) {
   switch (rdFieldTypes[key]) {
    case ("alpha"):
    if (theForm[key].value.length < min_alpha_length) {
      badFields.push(rdFieldNames[key]); valid=false;
     }
    break;
    case ("numeric"):
    if ( (!numeric_reg_exp.test(theForm[key].value)) ||
         (theForm[key].value.length < min_numeric_length) ) { 
       badFields.push(rdFieldNames[key]); valid=false;
      }
    break;
    case ("email"):
    if (!EMail_reg_exp.test(theForm[key].value.toLowerCase())) {
       badFields.push(rdFieldNames[key]); valid=false;
      }
    break;
    case ("phone"):
    if (!us_phone_reg_exp.test(theForm[key].value.replace(/[^\d]/g,''))) {
      badFields.push(rdFieldNames[key]); valid=false;
     }
    break;
   } // end switch(rdFieldTypes[key])
  } // end for (var key)
  if (valid == false) {
   for (var i=0; i<badFields.length; i++) {
     err += "Invalid Entry for " + badFields[i] + "\n";
   } // end for i
   alert(err);
  } // endif (!valid)
  return valid;
 } // end rdValidateForm()

The 'rdValidateForm' function tests four different form data types: text/alphabetic, text/numeric, email, and US telephone numbers whose names are included in the object 'rdFieldNames' and types are contained in 'rdFieldTypes' - which are both associative arrays. As browsers begin to support more HTML 5 input data types, you can add them to the 'rdFieldTypes' object which holds the field type definitions used by the code. For plain text fields, the code checks that the user's entry contains a minimum number of characters set in the variable 'min_alpha_length'. Similarly, for number fields, it checks for a minimum number of characters set in the variable 'min_numeric_length', but also checks that all of the characters are numbers from 0 to 9.

Even though HTML 5-compliant browsers will check for valid email addresses before my code is executed, I've included a regular expression that tests Email addresses (which accepts the new, longer Top Level Domain Names recently authorized by ICANN) so older browsers are supported. You're not liable to see those new TLDs often, but it's always best to be prepared for the future. The regular expression for telephone numbers is configured for basic US phone numbers without extension information. It will accept simple 7-digit numbers for local calls, or full 10-digit numbers that include an area code.

If my validation function detects a problem, it displays a warning message to the user that lists the names of all of the fields with improper data, and allows him to make corrections and try again. If the entries are all valid, the form data is processed normally.

HTML 5 is a major improvement for all web designers, and we've reached a point where the overwhelming majority of browsers in use today have excellent support for it. The question is no longer "Why would you use HTML 5?", it's "Why wouldn't you use HTML 5?". It was designed to be backward-compatible with older browsers, so by using HTML 5 you lose nothing and gain many valuable enhancements for your website. For more information, see "Dive Into HTML5"s article, Using forms with HTML 5.


This page was last modified on August 27, 2020



Copyright © 2005-2024 by Richard L. Trethewey - Rainbo Design Minneapolis. It's not that I think this is such an earth-shatteringly great presentation, but if you want to copy it, I'd appreciate it if you would ask for permission. I've been working with computers for over 30 years now, and one phrase keeps popping into my head - "I hate it when it's right!" And laptops and smartphones are no better.

Looking for more website design information? See my Sitemap!