Jump to content

How to use a custom validation object with JavaScript

+ 1
  dannyg1's Photo
Posted Sep 02 2009 12:38 PM

Use the code in the example below as a model for designing a single object that contains methods for each of your validation routines. The example uses modern event techniques for the form element's submit event binding and processing. With the help of the eventsManager.js library from "How to equalize the IE and W3C event models with Javascript", you can create a handy validation dispatching mechanism that can easily accommodate multiple forms on the same page.

Validation via a global object

<html>
   <head>
   <title>Recipe 8.5</title>
   <link rel="stylesheet" id="mainStyle" href="../css/cookbook.css" type="text/css" />
   <script src="../js/eventsManager.js"></script>
   <script type="text/javascript">
   // global validation object encapsulates validation routines
   var validator = {
       // validates that the field value string has one or more characters in it
       isNotEmpty : function(elem) {
           var str = elem.value;
           var re = /.+/;
           if(!str.match(re)) {
               alert("Please fill in the required field.");
               setTimeout("validator.focusElement('" + elem.form.name +
                 "', '" + elem.name + "')", 0);
               return false;
           } else {
               return true;
           }
       },
       //validates that the entry is a positive or negative number
       isNumber : function(elem) {
           var str = elem.value;
           var re = /^[-]?d*.?d*$/;
           str = str.toString();
           if (!str.match(re)) {
               alert("Enter only numbers into the field.");
               setTimeout("validator.focusElement('" + elem.form.name +
                 "', '" + elem.name + "')", 0);
               return false;
           }
           return true;
       },
       // validates that the entry is 16 characters long
       isLen16 : function(elem) {
           var str = elem.value;
           var re = /b.{16}b/;
           if (!str.match(re)) {
               alert("Entry does not contain the required 16 characters.");
               setTimeout("validator.focusElement('" + elem.form.name +
                 "', '" + elem.name + "')", 0);
               return false;
           } else {
               return true;
           }
       },
       // validates that the entry is formatted as an e-mail address
       isEMailAddr : function(elem) {
           var str = elem.value;
           var re = /^[w-]+(.[w-]+)*@([w-]+.)+[a-zA-Z]{2,7}$/;
           if (!str.match(re)) {
               alert("Verify the e-mail address format.");
               setTimeout("validator.focusElement('" + elem.form.name +
                 "', '" + elem.name + "')", 0);
               return false;
           } else {
               return true;
           }
       },
       // validate that the user made a selection other than default 
       isChosen : function(select) {
           if (select.selectedIndex == 0) {
               alert("Please make a choice from the list.");
               return false;
           } else {
               return true;
           }
       },
       // validate that the user has checked one of the radio buttons
       isValidRadio : function(radio) {
           var valid = false;
           for (var i = 0; i < radio.length; i++) {
               if (radio[i].checked) {
                   return true;
               }
           }
           alert("Make a choice from the radio buttons.");
           return false;
       },
       focusElement : function(formName, elemName) {
           var elem = document.forms[formName].elements[elemName];
           elem.focus();
           elem.select();
       }
   }
   
   // batch validation router tailored for "sampleForm"
   function validateSampleForm(form, evt) {
       if (validator.isNotEmpty(form.name1)) {
           if (validator.isNotEmpty(form.name2)) {
               if (validator.isNotEmpty(form.eMail)) {
                   if (validator.isEMailAddr(form.eMail)) {
                       if (validator.isChosen(form.continent)) {
                           if (validator.isValidRadio(form.accept)) {
                               return true;
                           }
                       }
                   }
               }
           }
       }
       if (evt.preventDefault) {
           evt.preventDefault();
       }
       evt.returnValue = false;
       return false;
   }
   
   // dispatcher, in case of multiple forms
   function dispatchValidation(evt) {
       evt = (evt) ? evt : window.event;
       if (evt) {
           var elem = (evt.target) ? evt.target : evt.srcElement;
           if (elem.name == "sampleForm") {
               validateSampleForm(elem, evt);
           }
       }
   }
   
   function setElementEvents() {
       addEvent(document.getElementById("sampleForm"), "submit", dispatchValidation, false);
       // set more element events here, if needed
   }
   // from eventsManager.js
   addOnLoadEvent(setElementEvents);
   </script>
   </head>
   <body>
   <h1>Form Validations</h1>
   <hr />
   <form method="GET" action="cgi-bin/register.pl"
       name="sampleForm" id="sampleForm">
   First Name: <input type="text" size="30" name="name1" id="name1"
       onchange="validator.isNotEmpty(this)" /> 
   
   Last Name: <input type="text" size="30" name="name2" id="name2"
       onchange="validator.isNotEmpty(this)" />
   
   E-mail Address: <input type="text" size="30" name="eMail" id="eMail"
       onchange="if (validator.isNotEmpty(this)) {validator.isEMailAddr(this)}" />
   
   Your Region: <select name="continent" id="continent">
       <option value="" selected>Choose One:</option>
       <option value="Africa">Africa</option>
       <option value="Asia">Asia</option>
       <option value="Australia">Australia/Pacific</option>
       <option value="Europe">Europe</option>
       <option value="North America">North America</option>
       <option value="South America">South America</option>
   </select>
   
   Licensing Terms:
       <input type="radio" name="accept" id="accept1" value="agree" />I agree
       <input type="radio" name="accept" id="accept2" value="refuse" />I do not agree
   
   
   <input type="reset" />
   <input type="submit" />
   </form>
   </body>
</html>


At the bottom of the script, the
addonloadEvent()
function forces the page's load event to invoke the
setElementEvents()
function. In this example, we assign only one event to a single element, a call to
dispatchValidation()
for the submit event of the form named
sampleForm
. This is where other scripted event bindings should be placed.

The
dispatchValidation()
function uses modern event processing to derive a reference to the form from which the submit event fired. There is only one form in this page, but the function accommodates additional forms by branching code to a specific validation router customized for the details of a particular form. Notice that a reference to the event object is passed to the validation router, along with a reference to the form element.

For this example, the form named
sampleForm
is validated through the
validateSampleForm()
function. Because this version uses modern event binding and processing, it includes both the W3C DOM and IE event model ways of preventing the form's default action from occurring.

Javascript & DHTML Cookbook

Learn more about this topic from Javascript & DHTML Cookbook, 2nd Edition.

In today's Web 2.0 world, Javascript and Dynamic HTML are at the center of the hot new approach to designing highly interactive pages on the client side. With this environment in mind, the new edition of this book offers bite-sized solutions to very specific scripting problems that web developers commonly face. Each recipe includes a focused piece of code that you can insert right into your application.

See what you'll learn


Tags:
0 Subscribe


0 Replies