jQuery Date Validation in Chrome

[Source: https://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:

102909 1920 jQueryDateV1

- as does IE (even IE6):

102909 1920 jQueryDateV2

- but which Chrome renders as an invalid date:

102909 1920 jQueryDateV3

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)));

    },

This article is part of the GWB Archives. Original Author: Elton Stoneman

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.