How can I specify a custom date formate to be validated with the Validation Plugin for jQuery?
How can I specify a custom date formate to be validated with the Validation Plugin for jQuery?
You can create your own custom validation method using the addMethod function. Say you wanted to validate "dd/mm/yyyy":
$.validator.addMethod(
"australianDate",
function(value, element) {
// put your own logic here, this is just a (crappy) example
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy."
);
And then on your form add:
$('#myForm')
.validate({
rules : {
myDate : {
australianDate : true
}
}
})
;
nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.
I personally use the very good http://www.datejs.com/ library.
Docco here: http://code.google.com/p/datejs/wiki/APIDocumentation
You can use the following to get your Australian format and will validate the leap day 29/02/2012 and not 29/02/2011:
jQuery.validator.addMethod("australianDate", function(value, element) {
return Date.parseExact(value, "d/M/yyyy");
});
$("#myForm").validate({
rules : {
birth_date : { australianDate : true }
}
});
I also use the masked input plugin to standardise the data http://digitalbush.com/projects/masked-input-plugin/
$("#birth_date").mask("99/99/9999");
Jon, you have some syntax errors, see below, this worked for me.
<script type="text/javascript">
$(document).ready(function () {
$.validator.addMethod(
"australianDate",
function (value, element) {
// put your own logic here, this is just a (crappy) example
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy"
);
$('#testForm').validate({
rules: {
"myDate": {
australianDate: true
}
}
});
});