1. Computing & Technology

JavaScript Form Processing

Required Fields

From , former About.com Guide

Even though browsers may not yet have processing built in to handle the new "required" attribute, we can add our own JavaScript that will allow us to use this attribute to handle when fields in our form are required.

Before we add the code though we need to consider just what we consider to be content when we consider that a field is required to be entered within the form. If we simply test for an empty string then people will easily bypass the required test by simply entering a space. We want them to enter something other than whitespace and so the simplest way of ensuring that something other than whitespace is entered is to trim any whitespace from the front and end of the string. Chances are that we will not want that whitespace anyway so we may as well trim it prior to processing the field.

JavaScript doesn't provide a trim method so we need to add it ourselves.


String.prototype.trim = function() {
var re = /^\s*(.*?)\s*$/;
return this.replace(re,"$1");}

With that code in place we can simply add the following function to do all of our required field validations and call it from where ever in our form field validations that we need to test if a required field is valid or not.


validateRequired = function(e,elem) {
if (elem === undefined) elem = whichElement(e);
elem.value = elem.value.trim();
if (elem.required && '' === elem.value) {
  errorMessage('Please enter values in all required fields.');
  stopDef();
  return false;
}
}

©2012 About.com. All rights reserved.

A part of The New York Times Company.