7

I've found this useful bit of code that allows uk dates to work in Chrome but I'm not sure how to implement it. It overrides the default date functionality.

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

How can I add this into jQuery validate to override the default functionality.

Here is where I found the code sample

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Mantisimo
  • 4,203
  • 5
  • 37
  • 55
  • I would suggest using something like: http://www.datejs.com/ – Mrchief Jul 28 '11 at 21:50
  • If you are going to copy an answer to another question, at least give that person the credit. (You've even copied their typos) http://stackoverflow.com/questions/5966244/jquery-datepicker-chrome – Christian Payne Jul 28 '13 at 23:47

1 Answers1

20

You should call the validator.addMethod method after loading the jquery.validate library like so:

$(function () {
    // Replace the builtin US date validation with UK date validation
    $.validator.addMethod(
        "date",
        function (value, element) {
            var bits = value.match(/([0-9]+)/gi), str;
            if (!bits)
                return this.optional(element) || false;
            str = bits[1] + '/' + bits[0] + '/' + bits[2];
            return this.optional(element) || !/Invalid|NaN/.test(new Date(str));
        },
        "Please enter a date in the format dd/mm/yyyy"
    );
});

Note that I used another way of actually validating the input, as the code in your question will not work (toLocaleDateString doesn't take a parameter). You could also change this to use the datejs library as Mrchief pointed out in the comments.

fretje
  • 8,322
  • 2
  • 49
  • 61