JavaScript
  Home arrow JavaScript arrow Page 2 - 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 
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 - Setting the basics of form validation: defining custom error objects


    (Page 2 of 4 )

    Before I start by defining the JavaScript functions that comprise the form validating program, I’d like to explain its logic, so when you see the source code, it will be much simpler to read and understand.

    Validating forms through exceptions is a pretty straightforward process, which closely resembles traditional client-side checking methods. For this particular case, I’ll set up a regular contact form comprised of some of the usual fields such as First Name, Last Name, Email and Comments. Then, I’ll define a function to check whether the fields have been filled in. In case it finds an offending field, the script will display an error message by using some DOM methods to modify the document’s structure. As you can see, the whole checking process is extremely understandable.

    So far, as described before, the logic for validating forms is nearly identical to that utilized with the usual techniques. However, the main difference rests on how errors are handled when a specific field hasn’t been filled in. Since JavaScript allows us to create custom error objects, each time the scripts find an offending field, an error object will be thrown within a “try” block and then trapped by the appropriate “catch” block.

    Once the error has been caught, the only thing to be done in order to get the validating script working is to define the proper error handlers. Of course, this process will be understood best if you’re able to study the code, thus I’ll begin defining the core “validateForm()” function, which looks like this:

    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;
    }

    As you can see, the above function checks to see whether the required fields have been filled in. In case the function finds an empty field, a custom error object is created and the proper warning message, together with the name of the offending field, are passed concatenated as one single argument for the error object constructor. This concept is clearly illustrated with the following lines:

    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');
    }

    Since all the custom error objects are created within the corresponding “try” block, they will be trapped by the “catch” statement and program flow will be moved to the “genericErrorHandler()” function, as listed below:

    catch(e){
        genericErrorHandler(e);
    }

    Additionally, the “valid” variable acts like a simple Boolean flag to indicate whether the form has been completed or not.

    Before I move on to writing the next functions, a brief explanation is in order here. Notice that no specific validation is performed on the email field. Probably, you might want to use a regular expression to make sure that at least a well-formed email address has been entered, similar to the following expression:

    if(!/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z])+$/.test
    (fields['email'].value)){
        throw new Error('email|Enter a valid email');
    }

    However, the reason for applying only basic validation is to overcome a bug of Internet Explorer, which is particularly slow in parsing regular expressions, causing error objects to be created and thrown before the regular expression engine finishes processing a given pattern. On the other hand, Firefox will process the error flawlessly.

    Now that you’re aware of this problem, I can move on to defining the corresponding functions for handling and displaying errors. Thus, join me in the next section to see how error handling is programmed.

    More JavaScript Articles
    More By Alejandro Gervasio


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

    JAVASCRIPT ARTICLES

    - Validating Digits and Dates with jQuery`s Va...
    - Validating Ranges, Emails, and URLs with jQu...
    - More Uses for the jQuery Tooltip Plug-in`s b...
    - Building Image-Based Tooltips with the jQuer...
    - Using the jQuery Tooltip Plug-in`s bodyHandl...
    - Using Rangelength, Min and Max with the Vali...
    - Using Minlength and Maxlength with the Valid...
    - Modifying Tooltip Coordinates with the jQuer...
    - Applying a Fade Out Effect with the jQuery T...
    - Tracking Mouse Movements with the jQuery Too...
    - Checking Online Forms with the Validator jQu...
    - Nested JavaScript Functions as Objects
    - The jQuery Tooltip Plug-in
    - Active Client Pages at the Server
    - ACP Tab Web Page







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT