Home arrow JavaScript arrow Page 2 - Exception Handling in JavaScript: Validating forms Introduction
JAVASCRIPT

Exception Handling in JavaScript: Validating forms Introduction


Here you have it. Welcome to the part four of the series “Exception handling in JavaScript.” Comprised of several parts, this tutorial introduces the usage of exceptions in JavaScript, by explaining the core concepts and demonstrating practical examples for fast application in numerous client-based programs.

Author Info:
By: Alejandro Gervasio
Rating: 4 stars4 stars4 stars4 stars4 stars / 8
October 04, 2005
TABLE OF CONTENTS:
  1. · Exception Handling in JavaScript: Validating forms Introduction
  2. · Setting the basics of form validation: defining custom error objects
  3. · Manipulating errors: defining custom error handling functions
  4. · Putting the pieces together: implementing the form validation script

print this article
SEARCH DEVARTICLES

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.


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials