SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Form Validation Made Easy : Expando Properties

This relatively obscure technique lets you turn HTML into a useful tool of your web application by allowing you to extend all the tags at your disposal to fit your specific needs. HTML is no longer just for formatting.

Remember that anything a browser doesn't understand, it simply skips over. Below I have created a textbox for which I have defined some custom attributes.

<INPUT date="MM/DD/YYYY" required name="myDate">

Obviously, older browsers can't make heads or tails of these non-standard attributes since they don't recognize it as a valid property of any HTML element. Internet Explorer 4, on the other hand, still makes these properties available to you as part of the document object model (DOM); it just doesn't know what to do with them.

The next step is learning to manipulate the attributes in script. Microsoft has provided three handy methods available on each and every object in the DOM. (Keep in mind that all values declared in HTML attributes are considered strings when accessed via script.)

  • getAttribute returns the current value of the property.
    	// "MM/DD/YYYY"
    	var myVal = document.myForm.myDate.getAttribute("date");

    (It is important to note that getAttribute ignores the case of the attribute name by default. I prefer to write attributes in lowercase, but others prefer everything inside tags to be in uppercase. Whether the attribute name is spelled "game" or "GAME" or even "GamE", getAttribute returns the correct value. It is also possible to access the attribute directly through dot notation, but this method is case-sensitive.)

    If an attribute does not exist, a call to getAttribute returns null. If a value was not supplied for the attribute, it returns the empty string.

    	// ""
    	myVal = document.myForm.myDate.getAttribute("required");
    
    	// null
    	myVal = document.myForm.myDate.getAttribute("integer");

    The power of getAttribute is in reading values of properties at run-time. Using run-time values allows you to customize the page interactively and perform any checks at appropriate times (e.g. onsubmit, onchange when validating a form).

  • setAttribute lets you update or create an attribute. The following code changes the value of the "date" attribute to "DD/MM/YYYY":
    	document.myForm.myDate.setAttribute("date","DD/MM/YYYY");
  • removeAttribute removes the attribute from the DOM as if it were never specified in the first place.
    	document.myForm.myDate.removeAttribute("date");

The beauty of expando attributes is their ability to store any kind of data format. You can go far beyond using these special attributes to store text. Any non-string value must be defined in script. Next we'll learn how to create pseudo-events with this technique.