Home arrow JavaScript arrow Page 4 - 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 - 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.

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