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

Inside Technique : Form Validation Made Easy
By Matthew Frank

As a web developer, you are often required to perform the same tasks repeatedly across pages and entire sites. One of the most tedious such task is form validation. Every form requires something a little different, whether requiring specific fields, checking dates or making sure someone entered a phone number correctly.

I included two different techniques for adding form validation. The first runs only on Internet Explorer 4.0 or later while the latter approach runs cross-browser. The IE-only technique is simpler to use and more powerful and is presented first. To support the same level of validation cross-browser support additional scripting is necessary. The cross-browser version is covered later in this article.

I have assembled a script which takes advantage of the document object model (DOM) available in Internet Explorer 4 and 5. As such, this script is only useful within applications targeted solely at these browsers. It will not cause problems in other browsers, but it won't perform its miracles, either.

The key techniques which represent the bulk of the script are as follows:

  • Expando properties - create, modify and delete your own properties for HTML elements
  • Pseudo-events - using expando properties, create your own events
  • Capturing event handlers - override and run pre-existing code
  • Methods as anonymous functions - mitigate the risks of name collisions when creating methods for your HTML elements; create consistent interfaces to processes which may change throughout your application's lifecycle.
  • Regular expression field validation - learn how to use the power of regular expressions to make validation simple and concise

By combining the above techniques with others already discussed at this site, my script can perform pre-defined field validation without any added code. Since I can't predict all the different types of validation you may need to use, I also created a framework in which you can easily add more of your own checks, which work in tandem with mine.

I have assumed a general understanding of JavaScript/JScript throughout the article. I refer you back to the many tutorials on SiteExperts.com if you get lost anywhere along the way.

Let's start by looking at expando properties.