JavaScript
  Home arrow JavaScript arrow Page 3 - Exception Handling in JavaScript: Validati...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Exception Handling in JavaScript: Validating forms Introduction
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 5
    2005-10-04

    Table of Contents:
  • Exception Handling in JavaScript: Validating forms Introduction
  • Setting the basics of form validation: defining custom error objects
  • Manipulating errors: defining custom error handling functions
  • Putting the pieces together: implementing the form validation script

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Exception Handling in JavaScript: Validating forms Introduction - Manipulating errors: defining custom error handling functions


    (Page 3 of 4 )

    In addition to the function responsible for throwing custom error objects, the script also exposes a set of functions tasked with trapping errors and displaying warnings, in accordance with the form fields that were left blank. With reference to catching errors, below is the definition for the “genericErrorHandler()” function:

    function genericErrorHandler(e){
        // get form field
        var obj=document.getElementsByTagName('form')[0].elements
    [e.message.split('|')[0]];
        if(!obj){return false}
        // get error message
        var errorMsg=e.message.split('|')[1];
        // display error message
        showError(obj,errorMsg);
    }

    Despite the simplicity of the function above, its functionality turns it into the workhorse of the script. As you can see, whenever a custom error object is thrown, the function determines the targeted offending field along with the error message to be displayed. The following line gets the corresponding form field:

    var obj=document.getElementsByTagName('form')[0].elements
    [e.message.split('|')[0]];

    The below expression obtains the appropriate error message:

    var errorMsg=e.message.split('|')[1];

    Once both parameters have been determined, they’re passed to the “showError()” function, which looks like this:

    function showError(obj,errorMsg){
        if(!obj.errorNode){
            obj.onchange=hideError;
            var spn=document.createElement('span');
            spn.appendChild(document.createTextNode(errorMsg));
            obj.parentNode.appendChild(spn);
            obj.errorNode=spn;
            obj.focus();
        }
        valid=false;
    }

    In simple terms, this function displays a warning message by creating on the fly a <span> element, which is appended to the offending field. Since an error has occurred, a custom “errorNode” property is created and assigned to the pertinent form field. By checking the existence of this property on subsequent calls, I’m easily avoiding the showing of multiple error messages for the same field.

    In a similar way, error messages are removed from the document structure by attaching an “onchange” event handler to the targeted form field, assuming that the user has modified its value to correct a bad entry. In accordance with this, the “hideError()” function is triggered whenever the data entered for that field is changed, thus here is how the mentioned function looks:

    function hideError(){
      this.parentNode.removeChild(this.errorNode);
      this.errorNode=null;
      this.onchange=null;
    }

    The task of the function above is simply to remove the error node (in short, the <span> element previously appended) and deactivate the “onchange” event handler, because hopefully the erroneous entry has been corrected by the user.

    At this point, all the relevant functions have been defined and explained. A quick way of testing the functionality of the whole checking script is to put all the pieces together and set up an example. Considering this, the next lines demonstrate how to implement an exception-based form validation script.

    More JavaScript Articles
    More By Alejandro Gervasio


       · The fourth part of the series implements an alternative method for performing...
     

    JAVASCRIPT ARTICLES

    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT