UK Date Validation For JQuery Validate

UK Date Validation For JQuery Validate

Recently I was making tweaks to a Monorail project and was required to add date validation. The default configuration using active record correctly applied the class “date” to the fields, which is a flag for JQuery validate.

Unfortunately, JQuery validate uses the American date format (mm/dd/yyyy). I had a play with the settings but could not find a hook to specify a UK date format. So I had to try something a bit different — I created a custom JQuery validate method.

You might also find this link useful: http://geekswithblogs.net/EltonStoneman/archive/2009/10/29/jquery-date-validation-in-chrome.aspxPreparation

To replicate my solution you’ll need a reference to three files:

·  JQuery

·  JQuery validate

·  Date.js (Date.js.com)

Laying down the rule

Using the validator I plugged in a new rule that parses the value using a date format. If the parse fails, then validation fails. This is where Date.js comes in — the Date.parseExact method. Notice the single characters for day and moth — this allows one or two digits.

$.validator.addMethod(

“validateDate”,

function (value, element) {

try {

if (!value) {

return true;

}

var d = Date.parseExact(value, “d/M/yyyy”);

if (d == null) {

return false;

} else {

return true;

}

}

catch (e) {

return false;

}

},

“Please enter a valid UK date dd/mm/yyyy”

);Apply the rule

The final step is to apply the validation to elements using a css selector. In this case I chose all items with a class called “validateDate”:

$(‘.validateDate’).validate({

name: “validateDate”

});Give it a whirl

Here is the result of using a weird American date format:

And here’s the result of being normal (not that I recommend it):

A full example

Here’s the sample html page I used to test it out. Don’t forget to download Date.js if you try it out.

Uk Date Validation