Overview

jQuery-Validate

jQuery-Validate allows you to add client side form validation in two easy steps. It uses the jQuery JavaScript Library and uses its familiar plugin syntax. You can see an example here of what you can accomplish.

Requirements

  • jQuery 1.4.x (not tested against 1.3.x)
  • Firebug or Firebug Lite (debugging only)

Usage

Step 1: Add this somewhere on your page:

<script>
   $(function(){
        $('form').validate();
   });
</script>

Step 2: To add rules to an input field (must be an input, select or textarea element) you need to specify your rules in the validate attribute:

<input type="password" name="password" size="24" validate="length:8" />
<input type="password" name="confirm" size="24" validate="required;match:password" />
<input type="text" name="email" size="24" validate="email" />

You can apply multiple rules by separating them with a semi-colon. Note that each rule is tested left to right and will not continue if one has failed. You might need to adjust the order in this case (see first example with the password above).

Options

  • debugLevel
    Uses the Firebug console to debug the plugin
    0: errors only, 1: warnings, 2: info
    default: 0
  • ajaxClass
    Class name to apply to the span tag when making an AJAX call
    default: ajax
  • spanErrorClass
    Class name to apply to the span tag when the input is not valid
    default: error
  • spanSuccessClass
    Class name to apply to the span tag when the input is valid
    default: success
  • inputErrorClass
    Class name to apply to the field when the input is invalid
    default: error

Rules

There are several basic rules included in the plugin:

  • ajax callback
  • custom callback
  • email
  • length min[, max]
  • match fieldName
  • regex re
  • required
  • username

ajax
The ajax rule requires a special callback function:

function checkUsername() {
    $.ajaxSetup({
        url: '/api',
        type: 'get',
        dataType: 'json',
        data: { f: 'users/username_available.json', username: this.val() },
        dataFilter: function(data, dataType) {
            if (dataType == 'json')
                data = $.parseJSON(data);
            return {
                msg: data.username + ' <strong>is not available :(</strong>',
                successMsg: data.username + ' <strong>is available!</strong>',
                valid: data.available
            };
        }
    });
}

Note that the ajax call is standard except that we use $.ajaxSetup() instead of $.ajax() and that we define a dataFilter callback function. This function needs to return an object as shown. The input field that called the function is available via this.

custom
This rule allows you to specify your own validation function. The function must be defined in the global namespace to be accessible. Example:

function checkUsername() {
    var re = /^[a-zA-Z][a-zA-Z0-9_]{0,15}$/;
    result = re.test(this.val());
    return {
        // successMsg: "username is valid", // Optional
        msg: "not a valid username",
        valid: result
    };
}

The input field can be accessed via this.

Expanding the preset rules

The rules can be expanded easily by adding your custom rules so they can be used globally and won't pollute your namespace. You need to create these custom inline functions after the plugin has loaded. For example:

$.fn.validate.rules.sayhi = function(argument) {
    var valid = false;

    if (this.val() == argument)
        valid = true;

    return {
        successMsg: "Hi :)", // Optional
        msg: "You didn't say Hello!",
        valid: valid;
    }
};

And to use it in your forms:

<input type="text" name="test" validate="sayhi:Hello!" />

Known Limitations

  • You cannot use semi-colons in the validation attribute for anything but separating the rules to apply.