Javascript Frameworks - Mootools Form Validation

MooTools is great. I am yet to upgrade to version 1.2 but will most likely integrate the latest version into my next project.

For those readers who think I am talking about a set of spanners for working on cows;

“MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API.” - http://mootools.net/

Admittedly I haven’t created anything spectacular as I use it predominantly as a time saving tool when developing web sites. Some practical uses that I have found for MooTools so far:

  • dropdown list population - using AJAX. Is very handy for lists where the second list is dependant on the first
  • showing / hiding content on a web page, e.g. toggle
  • lightbox tool for showing images - I use Roebox as it is very lightweight, e.g. view image
  • client-side form validation - simply enter a class for the input field e.g. class=”val_required”

Client-side Form Validation

The following shows how easy it is to validate forms using the Mootools framework.

View the demonstration of form validation in action

The javascript:

var fields = f.getElements('*[class^=val_]');
fields.each(function(element) {
  var lsElementName = jly_get_human_field_name(element.name);
  if((element.hasClass('val_required')) && (lsElementValue=='')){
    laValidateFields.push(new jly_validator(element,lsElementName+' is required.\n'));
    lbReturnValue = false;
  }
}

The HTML:

<input name="name" id="name" class="val_required" />
<input name="email" id="email" class="val_required val_email" />
 
 

As you can see, it is a very simple process of adding validation. All that is required is adding a class to the input field. The two examples shown here are val_required and val_email. Have a look at the source code of the demo for more information.

The demo uses alert boxes to inform the user that something is missing but you could take it a step further and add inline messages using MooTool’s injectAfter command.

Leave a Reply

You must be logged in to post a comment.