Tag Archives: plug-in

Added valid date validation in jQuery validator


Hi,
Recently I got lots of error on mobile page, where I cannot give a nice date picker.
I use jQuery validator for form validations, but its date validation is not validating valid date.

If you use the new Date() function with 32nd as date, then it takes next month’s date.

I came up with adding more validations in default date validation method.

(function($) {
	/*
	 * This is a date validation fix,
	 * Because earlier it was validating invalid dates like '12//2/12' or '04/31/2012'
	 */
	/*
	 * Edit 1: Added year range: 1012 is invalid year, SQL datetime range is 1/1/1753 TO 12/31/9999
	 */
	 $.validator.addMethod("date", function(value, element) {
		return this.optional(element) || (/^\d{2}([\/])\d{2}\1\d{4}$/.test(value) && !/Invalid|NaN/.test(new Date(value)) && parseInt(value.match(/^\d{2}/)) == (new Date(value).getMonth()+1) && parseInt(value.match(/\d{4}/)) > 1752);
	});
})(jQuery);

Save the above code in one js file e.g. jquery.validate.datefix.js and include it after you include jQuery validator js.