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

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

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
    if(!obj){return false}
    // get error message
    var errorMsg=e.message.split('|')[1];
    // display error message
// display errors
function showError(obj,errorMsg){
        var spn=document.createElement('span');
// hide errors    
function hideError(){
// validate form
function validateForm(){
        var fields=document.getElementsByTagName('form')[0].elements;   
        if(!fields){return false};
        // validate First Name field
            throw new Error('fname|Enter your First Name');
        // validate Last Name field
            throw new Error('lname|Enter your Last Name');
        // validate Email field
            throw new Error('email|Enter a valid email');
    // catch all errors
    return valid;
// execute 'validateForm()' when form is submitted
    var W3CDOM=document.getElementById&&document.
    // check if browser is W3CDOM compatible
            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">
<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;
<!-- contact form -->
<form method="post">
<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
<tr><td>&nbsp;</td><td><input type="submit" name="send"
value="Send Data" /></td></tr>


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

- 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 

Developer Shed Affiliates


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