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

Inside Technique : Form Validation Made Easy : Pseudo-Events

Assigning script code to an expando property allows you to create new events within the page. You have already seen how to add your own properties to elements on the page. Let's take that concept one step further and apply a function as a value to a property.

	<INPUT date="MM/DD/YYYY" required name="myDate">
	<SCRIPT language="JavaScript">
		function handleEvent(){
			alert("Event handled");
		}
		// assign handler via function pointer
		document.myForm.myDate.onvalidate=handleEvent;
	</SCRIPT>

So onvalidate has a value of a function instead of a string or number. In this example, onvalidate looks like any other event which you may want to script (e.g. onload, onblur).

Now we have established the event and event handler, but the browser does not recognize this event within its own object model; we are responsible for raising the event at the appropriate times. Be aware that the event object is not available from our pseudo-event since it is not a true event as defined in the DOM.

In our example above, we can add a function that checks that the value of the field is a date greater than today's date and raises the onvalidate event to notify us that the field has been validated:

	document.myForm.myDate.onvalidate();

Notice the use of parentheses after the onvalidate property in the dot notation; the parentheses indicate that the property is being treated as a function. But what happens when you define the event within the text of the HTML document itself?

   <INPUT date="MM/DD/YYYY" required name="myDate" 
          onvalidate="handleEvent();">

All text in the HTML is treated as a string; therefore, onvalidate has a string value, not a function value. The answer to our problem is to cast the string as a function inside the script. Since the event handler code may be written within the HTML, we should resort to using the getAttribute method to avoid problems with text case. You should also be careful to check that a handler function actually exists in the code or HTML before you try to run it.

function checkDate(){
  // check date here

  // The following line extracts the onvalidate property from
  // either dot notation or HTML source.

  var eEvent=document.myForm.myDate.getAttribute("onvalidate");
  if (eEvent){
    if(typeof eEvent!="function")
      eEvent=new Function(eEvent);
    return eEvent();
  }
  return true;  // date check completed without error
}

That takes care of any instance in which we define the onvalidate event handler, whether through script or within the HTML source. When dealing with pre-existing event handlers, you will need to learn how to capture and run event handlers in the context of your new handler.