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

    - Using jQuery to Preload Images with CSS and ...
    - Using Client-Side Scripting to Preload Image...
    - Removing Non-Semantic Markup when Preloading...
    - Using the Display CSS Property to Preload Im...
    - Preloading Images with CSS and JavaScript
    - Scaling and Moving Web Page Elements with th...
    - Fading, Hiding and Sliding HTML Elements wit...
    - Toggling CSS Properties with the GX JavaScri...
    - Cancel, Queue and Pause Animations with the ...
    - Producing Elastic Effects with the GX JavaSc...
    - Moving Divs Diagonally with the GX JavaScrip...
    - Moving Elements Vertically and Horizontally ...
    - Making Bouncing Effects in Parallel with the...
    - Creating Bouncing Effects with the GX JavaSc...
    - Manipulating Background Colors with the GX J...







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