How to fix jQuery 1.7 Date Validation for UK dates in Webkit browsers

Turns out the jQuery date validation in jQuery Validate from 1.7 is pretty screwed… it prevents valid UK dates from being submitted in Chrome and Safari and allows nonsense like 31/31/2012 through in Firefox.

Lots of people use the fix here: http://geekswithblogs.net/EltonStoneman/archive/2009/10/29/jquery-date-validation-in-chrome.aspx

But it doesn’t seem to work in Safari: luckily commenter ‘Mad’ points to an alternate solution in Microsoft’s AJAX library which seems to work great everywhere:

		// Fix for international date validation woes in jQuery Validate
		// as described here, but fix only for chrome: http://geekswithblogs.net/EltonStoneman/archive/2009/10/29/jquery-date-validation-in-chrome.aspx
		// alternate method as linked from comments here
		// http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
		// assign class 'date_international' to target datepicker text field instead of 'date'
		jQuery.validator.addMethod(
			"date_international",
			function(value, element) {
				var check = false;
				var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
				if( re.test(value)){
					var adata = value.split('/');
					var gg = parseInt(adata[0],10);
					var mm = parseInt(adata[1],10);
					var aaaa = parseInt(adata[2],10);
					var xdata = new Date(aaaa,mm-1,gg);
					if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
						check = true;
					else
						check = false;
				} else
					check = false;
				return this.optional(element) || check;
			}, 
			"Please enter a correct date"
		);

Slightly edited from http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js

Advertisements