JavaScript
  Home arrow JavaScript arrow Page 4 - Object-Oriented JavaScript: Building Real-...
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

Object-Oriented JavaScript: Building Real-World Examples
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 2 stars2 stars2 stars2 stars2 stars / 76
    2005-12-12

    Table of Contents:
  • Object-Oriented JavaScript: Building Real-World Examples
  • The first hands-on example: building object-based pop-up windows
  • Object-oriented AJAX: creating http requester objects
  • A final example: building quick and dirty form validating objects

  • 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


    Object-Oriented JavaScript: Building Real-World Examples - A final example: building quick and dirty form validating objects


    (Page 4 of 4 )

    As I mentioned earlier, custom JavaScript objects (as one would normally expect from any object) allow us to encapsulate specific functionality across different methods, in this way hiding behind their structure all the complexities required for performing a given task. This condition is particularly notorious when creating form validating objects, due to the fact that all the corresponding data checking routines can be wrapped up into methods and the overall form checking process can be easily performed by using compact and readable code.

    In order to illustrate the above concept, I’ll define a highly generic “Validator” constructor, which exposes some helpful methods for checking data entered in online forms, as well as for displaying and removing error messages for offending fields. Its signature is listed below:

    // define 'Validator' object
    function Validator(formObj){
        // assign object properties
        this.valid=true;
        this.fields=formObj.elements;
        // define 'validate()' method
        this.validate=function(){
            for(var i=0;this.fields.length;i++){
     if(!this.fields[i].value){
         this.showErrors(this.fields[i]);
         return this.valid;
     }
            }
        }
        // define 'showError()' method
        this.showErrors=function(obj){
            if(!obj.errorNode){
             obj.onchange=function(){
         this.hideError(obj);
     }
             var spn=document.createElement('span');
             spn.appendChild(document.createTextNode('Enter a value for this field'));
      spn.style.font='bold 12px Arial';
     spn.style.color='#c00';
             obj.parentNode.appendChild(spn);
             obj.errorNode=spn;
             obj.focus();
            }
            this.valid=false;
        }
        // define 'hideError()' method
        this.hideError=function(obj){
            obj.parentNode.removeChild(obj.errorNode);
            obj.errorNode=null;
            obj.onchange=null;
            this.valid=true;
        }
    }
     

    As you can see, the above constructor function takes the form to be validated as the only input parameter. Additionally, it assigns a couple of properties to the validating object, such as a flag variable “this.valid”, and the form fields which data validation will be performed on, in this case represented by the “this.fields” property.

    With reference to the relevant object methods, the first one, “validate()”, not surprisingly loops over the form fields and checks whether any of them contain an empty string. If a field is found to be empty, the “showError()” method will be invoked and the corresponding error message will be displayed next to the offending field. In a similar fashion, when values entered into fields are changed, the “hideError()” method will be called, resulting in any error legend being removed from the web document.

    If you’re not very concerned about client-side validation, this quick and dirty implementation of form validating objects can be considered valid. On the other hand, if your application demands strong JavaScript verification, you may want either to write more methods for the validating object, or look for another solution.

    All right, having defined the signature for generic form checking objects, let’s have a look at their possible implementation on a simple online form. Here’s the JavaScript snippet that checks form data:

    var theform=document.getElementsByTagName('form')[0];
    theform.onsubmit=function(){
        // instantiate 'Validator' object
        var formval=new Validator(theform);
        return formval.validate();
    }

    And, below it’s the simple web form, which validation is performed on:

    <form>
    <table>
    <tr><td>First Name</td><td><input type="text" name="fname" /></td></tr>
    <tr><td>Last Name</td><td><input type="text" name="lname" /></td></tr>
    <tr><td>&nbsp;</td><td><input type="submit" name="send" value="Send" /></td></tr>
    </table>
    </form>

    Here, you can see how basic client-side form validation can be performed by a tight fragment of JavaScript code. Basically, the above script creates a “Validator” object and takes as a parameter the form object for validation. Finally, all the data checking processes are carried out simply by calling the “validate()” method, after the form has been submitted. Indeed, the logic of the script is very understandable.

    Of course, if you want to copy and paste the source code for using “Validator” objects, here’s the complete list for the form validation script:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>USING VALIDATOR OBJECTS</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <script language="javascript">
    // define 'Validator' object
    function Validator(formObj){
        // assign object properties
        this.valid=true;
        this.fields=formObj.elements;
        // define 'validate()' method
        this.validate=function(){
            for(var i=0;this.fields.length;i++){
     if(!this.fields[i].value){
         this.showErrors(this.fields[i]);
         return this.valid;
     }
            }
        }
        // define 'showError()' method
        this.showErrors=function(obj){
            if(!obj.errorNode){
             obj.onchange=function(){
         this.hideError(obj);
     }
             var spn=document.createElement('span');
             spn.appendChild(document.createTextNode('Enter a value for this field'));
      spn.style.font='bold 12px Arial';
     spn.style.color='#c00';
             obj.parentNode.appendChild(spn);
             obj.errorNode=spn;
             obj.focus();
            }
            this.valid=false;
        }
        // define 'hideError()' method
        this.hideError=function(obj){
            obj.parentNode.removeChild(obj.errorNode);
            obj.errorNode=null;
            obj.onchange=null;
            this.valid=true;
        }
    }
    window.onload=function(){
        if(document.createElement&&document.
    getElementById&&document.getElementsByTagName){
            var theform=document.getElementsByTagName('form')[0];
             theform.onsubmit=function(){
         // instantiate 'Validator' object
        var formval=new Validator(theform);
         return formval.validate();
            }
        }
    }
    </script>
    </head>
    <body>
    <form>
    <table>
    <tr><td>First Name</td><td><input type="text" name="fname" /></td></tr>
    <tr><td>Last Name</td><td><input type="text" name="lname" /></td></tr>
    <tr><td>&nbsp;</td><td><input type="submit" name="send" value="Send" /></td></tr>
    </table>
    </form>
    </body>
    </html>

    Wrapping up

    Sadly, we’re done for now. In this series of tutorials, I’ve explored the most important points related to object-oriented JavaScript, explaining the basic concepts, as well as some unusual features such as “Function” objects, and the handy “constructor” and “prototype” properties, which become very useful for applying inheritance between objects. As a nice corollary for the series, I went through the development of some practical examples for creating helpful objects that can be used in different JavaScript applications.

    Hopefully, after reading this series, you’ve realized the excellent capabilities of JavaScript for creating and utilizing custom objects with relative ease, which can be a crucial topic, particularly when developing large client-side programs. As with everything in Web programming, the method you choose for writing your scripts will depend upon your personal taste and the requirements of each particular project. See you in the next tutorial!


    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.

       · This last tutorial shows some examples of how to create user-defined objects in...
       · [quote]The first improvement that comes to my mind is the addition of a “host”...
       · Hello Daniel,Thank you for commenting on my article. And, yes, you're correct on...
     

    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 3 hosted by Hostway
    Stay green...Green IT