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

Inside Technique : Form Validation Made Easy : Validation Method

Combining the use of regular expressions with the ability to create your own methods on form fields, we can create a common validation method for all form fields. If we loop through the elements of the form object and create the following method on each element, the validation of each field becomes a simple statement.

oElement.valid=function () {
  // REQUIRED
  if (this.getAttribute("required")!=null && !this.value){
    // The _err object holds and displays validation errors.
    // The _validation object has some useful methods and
    // constants as member objects.
    _err.add(this, _validation.REQUIRED, null);
    return false;
  }
  // DATE
  var format=this.getAttribute("date");
  if (format!=null && this.value) {
    // Set default date format
    format = _validation.setDefault(format, "MM/DD/YYYY");
    if (!_validation.isDate(this,format)){
      _err.add(this, _validation.DATE, format.toUpperCase());
      return false;
    }
  }

  return true;
}

Now that we have a valid method on each element, we can validate a given field with the following test.

if (oElement.valid()){
  // field passed validation
}else{
  // field failed validation
}

Now validating form data is as simple as adding attributes to INPUT tags. The attributes in the HTML tell the script how to validate any given field.

<INPUT required date="MM/DD/YYYY" onvalidate="alert('validated');">

The script I wrote with this article sets up all the necessary event handlers, methods and objects required to perform validation. All interfaces have been designed to be consistent and backwards-compatible with future versions of the script. Even if you're not interested in learning how it works, it is still a valuable tool for your applications.

You can now download the script and supporting files (including a sample form). Read through the whole script to see how everything comes together or just to find out more about the _err and _validation objects you see above.