JavaScript
  Home arrow JavaScript arrow Page 5 - Introducing Key Concepts for Form 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 
Sun Developer Network 
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

Introducing Key Concepts for Form Validation with the DOM
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 5
    2006-10-24

    Table of Contents:
  • Introducing Key Concepts for Form Validation with the DOM
  • Creating an old-fashioned form validation mechanism
  • Using the DOM for validating online forms
  • Removing error messages from the web page
  • Completing the 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


    Introducing Key Concepts for Form Validation with the DOM - Completing the validation script


    (Page 5 of 5 )

    Since the pair of JavaScript functions that I showed you in the previous section were responsible for displaying and removing error nodes from the corresponding web document, in consonance with the values entered on the online form, the only piece of the validation script that remains undefined is the function that checks whether all the required form fields has been filled in or not.

    To satisfy this requirement, below I coded a simple function, called "validateForm()," which not only verifies whether any required filed has been left blank, but it also calls the respective "showError()" function when applicable.

    Here is the signature of this new function. Take a look at its source code:

    // validate form function validateForm(formObj){           valid=true;            var fname=formObj.elements[0];            if(!fname){return};            if(!fname.value){showError(fname,'*Enter your First Name')};            var lname=formObj.elements[1];            if(!lname){return};            if(!lname.value){showError(lname,'*Enter your Last Name')};            var email=formObj.elements[2];            if(!email){return};            if(!email.value){showError(email,'*Enter your email
    address')};            var age=formObj.elements[3];            if(!age){return};            if(!age.value){showError(age,'*Enter your age (1-99)')};            var postadd=formObj.elements[4];            if(!postadd){return};            if(!postadd.value){showError(postadd,'*Enter your postal
    address')};            return valid; }

    In this case, I'm not going to bore you with irrelevant details of how the above function works, since I'm sure that you've worked with similar scripts hundreds of times. However, I'd like to highlight at least briefly how the referenced function calls "showError()" when a particular form field has been left empty.

    Of course, the validation process can be easily changed to perform a strict verification on each form field; consider this possibility seriously if you're going to use this script with your own web applications.

    Right, at this stage you've understood how each of the JavaScript functions defined previously works as an isolated piece, but I'm certain that you want to see them working together. Given that, below I listed the full source code for this DOM-based validation script, in conjunction with the corresponding (X)HTML markup.

    Here's the script in question, ready to be copied and pasted:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>DOM-based form validator</title> <script language="javascript"> // validate form function validateForm(formObj){             valid=true;             var fname=formObj.elements[0];             if(!fname){return};             if(!fname.value){showError(fname,'*Enter your First
    Name')};             var lname=formObj.elements[1];             if(!lname){return};             if(!lname.value){showError(lname,'*Enter your Last
    Name')};             var email=formObj.elements[2];             if(!email){return};             if(!email.value){showError(email,'*Enter your email
    address')};             var age=formObj.elements[3];             if(!age){return};             if(!age.value){showError(age,'*Enter your age (1-99)')};             var postadd=formObj.elements[4];             if(!postadd){return};             if(!postadd.value){showError(postadd,'*Enter your postal
    address')};             return valid; } // display error messages function showError(obj,message){             if(!obj.errorNode){                         obj.onchange=hideError;                         var span=document.createElement('span');                         span.appendChild(document.createTextNode
    (message));                         obj.parentNode.appendChild(span);                         obj.errorNode=span;             }             valid=false;             return } // hide error messages function hideError(){             this.parentNode.removeChild(this.errorNode);             this.errorNode=null;             this.onchange=null; } // execute 'ValidateForm()' function when page is loaded window.onload=function(){             // check if browser is W3CDOM compatible             if(document.getElementById&&document.
    getElementsByTagName&&document.createElement){                         var theform=document.
    getElementsByTagName('form')[0];                         if(theform){theform.onsubmit=function()
    {return validateForm(this)}};     } } </script> </head> <body> <div id="formcontainer"> <form action="processform.php" method="post"> First Name <input type="text" name="fname" /><br /> Last Name <input type="text" name="lname" /><br /> Email <input type="text" name="email" /><br /> Age <input type="text" name="age" /><br /> Postal Address <input type="text" name="paddress" /><br/> Comments<br/> <textarea rows="10" cols="20"></textarea><br /> <input type="submit" name="send" value="Send Data" /> </form> </div> </body> </html>

    Final thoughts

    In this first article of the series, I hopefully demonstrated how to create a simple form validation script that uses the DOM for displaying and removing error messages from the corresponding web document. But if you're already tested the script, certainly you'll have noticed that it really lacks a good look and feeling.

    That's why in the next part, I'll be adding some styles to the original form checking application so it can look a bit more polished and professional. Meet you in the next article!


    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.

       · In this first part of the series, you'll learn how to use the DOM, in order to...
       · Hi:I would have loved to read your article, but when I increase the text size...
       · Hi, tedd. All of our sites are designed for 1024x768 resolution. The...
       · Hello Ted,Thank you for your interest on my DOM article. As Robert gently said...
     

    JAVASCRIPT ARTICLES

    - More on JavaScript Array Objects
    - Methods of the DOM Location Object
    - The DOM Location Object Properties
    - Handling Remote Files with JavaScript Click ...
    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...


     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     





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