JavaScript
  Home arrow JavaScript arrow Page 4 - 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  
Moblin 
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 - Putting the pieces together: implementing the form validation script


    (Page 4 of 4 )

    Now that you know all the functions involved in checking forms, it’s time to put them together and make the script do its business. In order to have all the source code available in one place, here is the full list for the checking script:

    // generic error handler
    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);
    }
    // display errors
    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;
    }
    // hide errors    
    function hideError(){
      this.parentNode.removeChild(this.errorNode);
      this.errorNode=null;
      this.onchange=null;
    }
    // validate form
    function validateForm(){
        valid=true;
        try{
            var fields=document.getElementsByTagName('form')[0].elements;   
            if(!fields){return false};
            // validate First Name field
            if(!fields['fname'].value){
                throw new Error('fname|Enter your First Name');
            }
            // validate Last Name field
            if(!fields['lname'].value){
                throw new Error('lname|Enter your Last Name');
            }
            // validate Email field
            if(!fields['email'].value){
                throw new Error('email|Enter a valid email');
            }
        }
        // catch all errors
        catch(e){
            genericErrorHandler(e);
        }
        return valid;
    }
    // execute 'validateForm()' when form is submitted
    window.onload=function(){
        var W3CDOM=document.getElementById&&document.
    getElementsByTagName&&document.createElement;
        // check if browser is W3CDOM compatible
        if(W3CDOM){
            document.getElementsByTagName('form')[0].onsubmit=function(){
                return validateForm();
            }
        }
    }

    With reference to the above script, a few things should be noted. First, I’ve kept data checking routines very simple, but you’re able to adapt the code to work with stricter validation. And second, I’ve attached an “onsubmit” event handler, in order to trigger the “validateForm()” function when the form is submitted.

    Of course, the example would be rather incomplete without showing the corresponding form. Additionally, I’ve included some CSS declarations for styling the overall form’s appearance, so here’s what it looks:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>FORMVALIDATION EXAMPLE</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    <style type="text/css">
    table {
        border: 1px solid #000;
        padding: 5px;
        background: #ccf;
        font: bold 11px Verdana, Arial, Helvetica, sans-serif;
        color: #000;
    }
    td.small {
        width: 100px;
        text-align: right;
    }
    td.large {
        width: 400px;
        text-align: left;
    }
    .field {
        font: normal 12px Arial, Helvetica, sans-serif;
        color: #000;
        width: 250px;
        border: 1px solid #000;
    }
    textarea {
        font: Arial, Helvetica, sans-serif;
        color: #000;
        width: 250px;
        height: 150px;
        border: 1px solid #000;
    }
    span {
        font: bold 11px Verdana, Arial, Helvetica, sans-serif;
        color: #c00;
    }
    </style>
    </head>
    <body>
    <!-- contact form -->
    <form method="post">
    <table>
    <tr><td class="small">First Name</td><td class="large"><input
    type="text" name="fname" class="field" /></td></tr>
    <tr><td class="small">Last Name</td><td class="large"><input
    type="text" name="lname" class="field" /></td></tr>
    <tr><td class="small">Email</td><td class="large"><input
    type="text" name="email" class="field" /></td></tr>
    <tr><td class="small">Comments</td><td class="large"><textarea
    name="comments"></textarea></td></tr>
    <tr><td>&nbsp;</td><td><input type="submit" name="send"
    value="Send Data" /></td></tr>
    </table>
    </form>
    </body>
    </html> 

     

    As you can see, the above page displays the sample contact form, which has been wrapped into a table structure. Also, as I said before, some styles have been specified for improving the look and feel of the form, but this can be easily modified to fit specific needs. Surely you’ll find the styles that best suit your requirements.

    To wrap up

    That’s all for now. Over this fourth part of the series, I explained through a concrete example how JavaScript exceptions can be used to implement form validation within web programs. In addition to using the already familiar “try-catch” blocks, the example went through the advantages of creating custom error objects for performing form data checking, by explaining an alternative method to traditional form verification.

    In order to demonstrate some additional applications of exceptions, in the last part of the series I’ll explain how to deal with browser incompatibilities, particularly in the terrain of object instantiation. You won’t want to miss it!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

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

    JAVASCRIPT ARTICLES

    - 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
    - Ajax Hack for Entering Information Without R...
    - EXT JS 2.1 Overview
    - Using the Style Object for Zebra Tables with...
    - Binary Searching
    - An Improved Approach to Building Zebra Tables






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