JavaScript
  Home arrow JavaScript arrow Page 10 - Form Validation with JavaScript
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
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? 
Google.com  
JAVASCRIPT

Form Validation with JavaScript
By: Nariman K, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 322
    2003-12-01


    Table of Contents:
  • Form Validation with JavaScript
  • Check Point
  • Object Lessons
  • Rock On
  • Hammer Time
  • How Things Work
  • A Little Space
  • Expressing Yourself
  • Under Construction
  • A Quick Snack

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    Form Validation with JavaScript - A Quick Snack
    ( Page 10 of 10 )

    At this stage, I think I have enough building blocks to actually begin using this class to perform form input validation. Let's build a simple form, and also add the JavaScript to validate the data entered into it. Note that the form validation object created on the previous page is stored in the file "formValidator.js," which is read in near the top of the page.

    <html>
    <head>
    <basefont face="Arial">
    <script language="JavaScript" src="formValidator.js">
    </script>
    <script language="JavaScript">
    
    // check form values
    function checkForm()
    {
    
    	// instantiate object
    	fv = new formValidator();
    	
    	// perform checks
    	// check for empty name field
    	if (fv.isEmpty(document.forms[0].elements[0].value))
    	{
    		fv.raiseError("Please enter a name");
    	}
    
    	// check for empty age field
    	if (fv.isEmpty(document.forms[0].elements[1].value))
    	{
    		fv.raiseError("Please enter an age");
    	}
    
    	// check for valid age range
    	if (!fv.isWithinRange(document.forms[0].elements[1].value, 
    		1, 99))
    	{
    		fv.raiseError("Please enter an age in the 
    		range 1-99");
    	}
    
    	// check for empty email address
    	if (fv.isEmpty(document.forms[0].elements[5].value))
    	{
    		fv.raiseError("Please enter an email address");
    	}
    
    	// check for valid email address format
    	if (!fv.isEmpty(document.forms[0].elements[5].value) &&
    	!fv.isEmailAddress(document.forms[0].elements[5].value))
    	{
    		fv.raiseError("Please enter a valid email address");
    	}
    
    	// check for checkbox
    	if (!fv.isChecked(document.forms[0].elements[6]))
    	{
    		fv.raiseError("Please indicate your agreement with 
    				this site's terms and conditions");
    	}
    
    	// all done
    
    	// if errors, display, else proceed
    	if (fv.numErrors() > 0)
    	{
    		fv.displayErrors();
    		return false;
    	}
    	else
    	{
    		return true;
    	}
    	
    }
    
    </script>
    </head>
    
    <body>
    
    <form action="action.cgi" method="POST" 
    		onSubmit="return checkForm()">
    
    <b>Name:</b>
    <br>
    <input type="text" name="name" size="15">
    
    <p>
    
    <b>Age:</b>
    <br>
    <input type="text" name="age" size="2" maxlength="2">
    
    <p>
    
    <b>Sex:</b>
    <br>
    <input type="Radio" name="sex" value="m" checked>Male
    <input type="Radio" name="sex" value="f">Female
    
    <p>
    
    <b>Favourite sandwich type:
    <br>
    <select name="stype">
    <option value="1">Thin crust
    <option value="2">Thick crust
    <option value="3">Toasted
    </select>
    
    <p>
    
    <b>Email address:
    <br>
    <input type="text" name="email" size="25">
    
    <p>
    
    <input type="Checkbox" name="agree">
    I agree to the terms and conditions of this site
    
    <p>
    
    <input type="Submit" name="submit" value="Save">
    </form>
    
    </body>
    </html>
    


    In this case, when the form is submitted, the "onSubmit" event handler invokes the checkForm() function, which instantiates a new object of the formValidator class. Once this object has been instantiated, all the validation routines defined earlier become available to the script as object methods, and can be used to test the various input values provided in the form.

    Let's see if it works. Here's what happens when I try submitting the form with no fields filled in:

    * Error: Please enter a name 
    * Error: Please enter an age
    * Error: Please enter an age in the range 1-99
    * Error: Please enter an email address 
    * Error: Please indicate your agreement with this 
    site's terms and conditions
    


    And here's what happens when I submit the form with incorrect data in the age field:

    * Error: Please enter an age in the range 1-99
    


    Only when all the errors have been corrected, and the user's input passes all the validation tests, will the function checkForm() return true and the form get submitted to the form processing script. In this way, input validation can prevent erroneous data from corrupting your database.

    Of course, you can perform input validation without using an object (as demonstrated in the very first example in this article). However, developers typically perform pretty standard tasks when validating form input; instead of writing (and rewriting) the same code over and over for each of your projects, it makes more sense to create a simple, reusable library of functions, encapsulate them in an object, and plug that object into your forms as and when needed.

    It's important to note that the object above is still fairly primitive. If you plan to use it in a live environment, you should modify it to include more stringent error checking. (I've omitted this in the example above to make the code a little easier to read and explain.) You might also want to add more validation methods to it as and when you need them, so to build a library that you can reuse over and over again, for different applications and requirements.

    And that's about all for the moment. In this article, you expanded your knowledge of JavaScript's OOP capabilities by actually using all that theory to build something useful - a form validation widget which can be used to verify the data entered into an online form, and provide a way for you to take action in case the data entered by the user does not met your expectations.

    If you're a stressed-out Web developer working on a Web site, a Web application or an embedded system, you might find this object a handy tool in your next development effort. If you're a novice programmer struggling to understand how OOP can make your life easier, I hope this article offered some pointers, as well as some illustration of how object-oriented programming works. And if you don't fit into either of those categories - well, I hope you found it interesting and informative, anyway.

    See you soon!

    Note: All examples in this article have been tested in Microsoft Internet Explorer 6. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article.

     
     
    >>> More JavaScript Articles          >>> More By Nariman K, (c) Melonfire
     

       

    JAVASCRIPT ARTICLES

    - Introduction to JavaScript
    - Adding Elements to a Tree with TreeView jQue...
    - Using the Persist Argument in a TreeView jQu...
    - Using Unique and Toggle in a TreeView jQuery...
    - Using Event Delegation for Mouseover Events ...
    - Using the Animate Option in a Treeview jQuer...
    - Using HTML Lists with Event Delegation in Ja...
    - Opened and Closed Branches on a TreeView jQu...
    - Mouseover Events and Event Delegation in Jav...
    - Creating a TreeView JQuery Hierarchical Navi...
    - Event Delegation in JavaScript
    - A Look at the New YUI Carousel Control
    - Working with Draggable Elements and Transpar...
    - Displaying Pinned Handles with Resizable Con...
    - Building Resizable Containers with the Ext J...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek