JavaScript
  Home arrow JavaScript arrow Page 3 - Universal Form Validation
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

Universal Form Validation
By: Justin Cook
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 24
    2004-02-02

    Table of Contents:
  • Universal Form Validation
  • First, the Forms
  • Good Form, Jack!
  • Pick a Number, Any Number!
  • And Knowing is Half the Battle

  • 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


    Universal Form Validation - Good Form, Jack!


    (Page 3 of 5 )

    I’m absolutely certain that the most pressing thought racing through your mind this very moment is ‘how on Earth could we accomplish such a great feat by the use of only one function?’ Ok, more likely is that the real pressing thought you have is wondering whether or not to eat that leftover pizza for breakfast.

    Regardless of that, I’m going to answer both questions. Yes, eat the pizza. Who knows what kind of valuable bacteria may have multiplied overnight. As for the forms, all we need to do is find some way of handling all possible circumstances that may exist and check for validity of the required fields. If we can determine the entries for each to be sufficient, then we can submit the form. Otherwise, we barf out one of those bothersome messages making the user fully aware of their deficiencies. Let’s walk through the code.


    function checkForm) { 
     
    var strMessage 'Please fix the following:nn';
     
    var objTemp
     
    var strName ''
     
    var boolIsValid true;
     
    for ( var 0
      i 
    f.elements.length
      i
    ++ ) {

    So, we’ve specified ‘f’ as the form we’re going to check, and to do that we’ll iterate though each field, or element, within the form. We’ve set the initial error message, and the Boolean flag to throw up if an element is invalid.


    objTemp f.elements[i];
    strName 
    objTemp.name
    if 
    strName.substr
         strName
    .length ) == 
         
    '_required' ) {

    So you can see that we’re only going to work with required elements. We don’t care about anything else, quite frankly!


    //strName = 
    // strName.replace( /data_/, '' );
    strName = strName.replace( /_required/, '' );
    strName = strName.replace( /_/g, ' ' );
    strName = strName.toLowerCase();

    We’ve accomplished a number of things here. If you’re concerned with the first, commented-out line, you’ll have to read right through to the conclusion the chilling answer to that mystery. The next removes three lines prepare the name for the error message, by removing the ‘_required’ suffix, but spacing out the words, and by making it all a nice, readable lower case.


    if objTemp.value == '' ) {
     boolIsValid 
    false;
     strMessage 
    += strName ' is emptyn';
    } else if ( objTemp.type == 'radio' ) {
     boolIsValid 
    false;
     
    for ( var 0objTemp.lengthj++ ) {
      
    if ( objTemp[j].checked ) {
       boolIsValid 
    true;
       
    break;
      
    }
     
    }
    }

    This is the first round of checking. First off we can simply look for an entry other than ‘’. That simply doesn’t work for radio buttons however, so we are forced to search through them all to find at least one that is checked. Next we can move on to more specific targets.


    if (strName.indexOf('first name') != -
         
    && objTemp.value == 'First' ) {
     boolIsValid 
    false;
     strMessage 
    += strName 
     
    ' is invalidn';
    } else if (strName.indexOf('last name') != -
      
    && objTemp.value == 'Last' ) {
     boolIsValid 
    false;
     strMessage 
    += strName ' is invalidn';

    Here I have added in a little code just to check that the default values have not been left in the first and last name field. I often place the ‘First” and ‘Last’ right in the fields as a tool tip, and have it disappear when focused on the field. This will ensure they’ve at least entered some name, even if it is Richard Simmons, or my favorite, Jim Bob.


    } else if 
     
    (strName.indexOf('email') != -&& 
     
    (objTemp.value.indexOf(<A href="mailto:'@'">'@'</A>) == -
     
    || objTemp.value.indexOf('.')== -1)) 
     
    {
      boolIsValid 
    false;
      strMessage 
    += strName ' is invalidn';

    This is an over-simplified email checking, checking only for an ‘@’ and a ‘.’. I highly recommend using a regular expression for this, but I don’t want to step on Melonfire’s toes. You can use his, found at http://www.devshed.com/c/a/JavaScript/Form-Validation-with-JavaScript/7/.


    } else if 
      
    (strName == 'verify password' && 
      
    (objTemp.value 
      
    != f.data_password_required.value)){
       boolIsValid 
    false;
       strMessage 
    += 'Passwords do not match!n';
      
    }
     
    }
    }

    This was something I threw in once for an application where new users were signing up. This would make sure they typed the same password twice. I didn’t totally need to include this in the article, but I left it in to demonstrate just how flexible the function is. You can really add in any routine to check any circumstance you come up against, and so long as you have the ‘_required’ attached to the new fields.


     if ( boolIsValid == true ) {
      
    return true;
     
    } else {
      alert
    strMessage );
     
    return false;
     
    }
    }

    This is the last little piece of the pie. We here check if our Boolean flag has been tripped, and raise the alarm if it has. Now, you could get fancy and re-focus the user on the first missing element, but once again that’s entirely up to your creative customization skills.

    If data has been entered, then the form is off to the cleaners. However, what happens when you see entries in your database with a phone number of 1-800-YOU-WISH, or an age of ‘asdf’? These are supposed to be numbers! NUMBERS! And our amazing universal form checker let them through just because they were more than nothing! How can we handle such situations? Perhaps we could continue to modify the form checker to check for numeric values for fields name ‘phone’ and ‘age’, but we’d spend the rest of our waking lives adding ‘year’ and ‘day’ and every other numeric field to the list. There’s got to be a better way! Oh yes, read on…

    More JavaScript Articles
    More By Justin Cook


     

    JAVASCRIPT ARTICLES

    - 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...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget






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