[Source: http://geekswithblogs.net/EltonStoneman]
We had a fiddly issue with date validation in an ASP.NET MVC page failing for a valid date in Chrome, but passing in Firefox, IE etc. Tracing through our own code and xVal, the issue was narrowed down to the jQuery validation plugin (jquery.validate.js). For simple date validation, the library instantiates a date object from the given text value and lets JavaScript raise errors for invalid dates:
date: function(value, element) {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
},
Chrome seems to ignore the current locale when it creates the date object, so a valid date in UK dd/mm/yy format – 29/10/2009 – fails as Chrome seems to interpret it in US mm/dd/yy format. Easy to test outside of all other code by entering some simple JavaScript into the address bar:
javascript:new Date(’29/10/2009′).toString()
Which Firefox renders as expected:
as does IE (even IE6):
– but which Chrome renders as an invalid date:
You can also test it by navigating to the jQuery date validation sample page, and checking results for the same date in different browsers.
The fix is a simple change to the jQuery script to force the use of the current locale:
// http://docs.jquery.com/Plugins/Validation/Methods/date
date : function(value, element) {
// ES - Chrome does not use the locale when new Date objects instantiated:
// return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
var d = new Date();
return this.optional(element) ||
! / Invalid | NaN /.test(new Date(d.toLocaleDateString(value)));
}
,
posted on Thursday, October 29, 2009 2:20 PM