Jake Jake - 7 months ago 27
Javascript Question

jqueryUI Datepicker plus Validator in dd/mm/yyyy format

I have a form with a jQuery UI Datepicker, which then gets validated using the jQuery Validation plugin.

Datepickers are created using:

$("#dob").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: "dd/mm/yy",
onSelect: function (){
this.focus();
},
});


However the validation plugin seems to validate in the US format when I require it to validate using dd/mm/yyyy. This means that any date past the 12th of any month is deemed invalid.

I have looked around and I found a method to add a different way to validate the date using a regular expression:

$.validator.addMethod(
"australianDate",
function(value, element) {
return value.match(/^(0?[1-9]|[12][0-9]|3[01])\/(0?[1-9]|1[012])\/((19|20)\\d\\d)$/);
},
"Please enter a date in the format dd/mm/yyyy."
);


which is then added to the rules:

dob:{
required:true,
australianDate: true
},


but this still seems to fail for any input.

the regular expression I am using is one I have used in the past with php and is a bit more accurate then the generic (any2numbers/any2numbers/any4numbers) expression, and I would like to be able to use it in the javascript aswell.

Do javascript regular expressions need to be in a different format to php? is that where I am going wrong..

Any help is greatly appreciated.

Answer

Thanks for your input. While both answers did work, they did not validate things like leap years or Feb must be max 28/29..

I kept looking around and managed to find another jquery plugin simply called date.js.

once linked you simply have to call the Date.parseExact function:

jQuery.validator.addMethod("australianDate", function(value, element) { 
    return Date.parseExact(value, "d/M/yyyy");
}, "Please enter a valid date in the format dd/mm/yyyy.");

Validates leap years and everything else I have tested correctly.

Comments