Click here to Skip to main content
15,881,424 members
Articles / Programming Languages / Javascript
Tip/Trick

Extending the jQuery validation plug-in

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
18 Mar 2013CPOL4 min read 21.2K   218   4   1
Making modifications to the standard jQuery validation behaviour.

Introduction

This jQuery validation plug-in can be changed and tailored to meet most requests from a business. This article shows some that I have been asked to do recently.

Background

  • "Can you make the text red too"
  • "Can you remove the messages and just do a count"
  • "Can you make it more understandable"

It's quite common for me, during a project, to get requests for changes to the look and feel of forms based on the designs, which don't quite match up with the behaviour of the standard jQuery validation behaviour (http://docs.jquery.com/Plugins/Validation). This article is a summary of some of these changes that I've worked out to act as a reminder to me and to hopefully save other people a bit of Googling.

Based on the original examples on the jQuery site I've combined them all together into three files; a html file, a js file, and a CSS file. This gives good separation between the function, the style and the layout.

There are several ways of telling the jQuery what to validate but a simple clean way is by using classes on the html controls. This allows you to abstract everything programming but the class names to the js file.

HTML
<input id="pcode" name="pcode" type="text" maxlength="20" class="postcode">

and they can be combined to build up more complicated validation.

HTML
<input id="phone" name="phone" type="text" maxlength="50" class="required phone">

Adding new validators

A common request is for a slightly different set of validators from the default ones. This is mainly as I work on UK and European sites and the address and data formats are different.

An example of a new validator is to do a basic check for a UK postcode which returns a boolean on the result of the test. Also it has the optional test in case a postcode isn't available. Adding the optional test is good because its better to only test for one thing in a validator at once and to test whether the value is required separately.

JavaScript
$.validator.addMethod(
  "postcode",
  function (value, element) { 
    var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|
	[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/;
    var re = new RegExp(regPostcode);    
    return this.optional(element) || re.test(value);
  }, "Please correct the postcode"
);

The code declares a method of name postcode which matches the class on the input control. This then uses the regex library to test the value passed in and return a boolean result. The OR operator and this.optional(element) let the code validate as true if the value is missing.

Stopping normal behaviour

Another popular request is to remove the validation messages completely and just have the controls style change. Either to have the linking labels highlight the error or simply just put only a red border around the fields.

The validation library adds a class to the input controls that fail validation called error and so you can style for that happening using input.error in the CSS.

input.error, textarea.error, select.error { border: 1px solid red; } 

No messages

To remove the messages globally for all validators of a particular type to you can set the default message to an empty string

JavaScript
$.validator.messages.required = "";
$.validator.messages.email = "";

For the new validator you can either set it an empty string in the same way or just set the last parameter in the declaration to an empty string. So in the postcode example above, replacing the string "Please correct the postcode" to "".

Highlight using the labels

In order to highlight with the label for a particular input control we need to get jQuery to identify that particular label, so the CSS can work on it. This solution relies on there being a div tag around any text we want to change and it being next to the input control.

When the validation fails we can override the highlight and unhighlight options for the form and go in the DOM and find the sibling control which is a div and add the error class to it.

JavaScript
highlight: function(element, errorClass, validClass) { //
  $(element).siblings('div').addClass('error');
}

unhighlight: function(element, errorClass, validClass) { 
  $(element).siblings('div').removeClass('error');
}

This then means the label can be turned red using CSS.

JavaScript
.error { color: red; }

Note that overriding the options replaces the default behaviour of adding the error class to the controls. So to add it back in, you can cut and paste from the main jQuery validator file jquery.validate.js for unhighlight.

JavaScript
if (element.type === 'radio') {
  this.findByName(element.name).removeClass(errorClass).addClass(validClass);
} else {
  $(element).removeClass(errorClass).addClass(validClass);
}

and for highlight:

JavaScript
if (element.type === 'radio') {
  this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
  $(element).addClass(errorClass).removeClass(validClass);
}

after the lines to affect the class of the label.

Summary control

Finally if you need to write an unusual summary control then you can override the option showErrors to update a label control while including:

JavaScript
this.defaultShowErrors();

to keep the default behaviour.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Prasad Khandekar20-Mar-13 22:21
professionalPrasad Khandekar20-Mar-13 22:21 
Thank's for the article David.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.