Home arrow JavaScript arrow Page 4 - Object-Oriented JavaScript: Building Real-World Examples
JAVASCRIPT

Object-Oriented JavaScript: Building Real-World Examples


In the first two parts of this series, we've explored the most important points related to object-oriented JavaScript. In this final part, we go through the development of some practical examples for creating helpful objects that can be used in different JavaScript applications.

Author Info:
By: Alejandro Gervasio
Rating: 2 stars2 stars2 stars2 stars2 stars / 93
December 12, 2005
TABLE OF CONTENTS:
  1. · Object-Oriented JavaScript: Building Real-World Examples
  2. · The first hands-on example: building object-based pop-up windows
  3. · Object-oriented AJAX: creating http requester objects
  4. · A final example: building quick and dirty form validating objects

print this article
SEARCH DEVARTICLES

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.

blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials