25

When using jQuery UI Datepicker, we encouter a problem when used in Google Chrome: when we enter a date with a day higher than 12, it does not accept it as a valid date, this is because chrome thinks the dateformat is mm/dd/yyyy. We tried to solve this by adding code to try to force the date settings into dd/mm/yyyy

$('.date').datepicker({ dateFormat: "dd/mm/yy" });

Is there any way to resolve this issue, so our datepicker will accept dd/mm/yyyy values? We only have this issue in google Chrome, the datefix works for firefox, ie & safari. We are using ASPX & MVC3 with this project.

If someone could solve our issue, that would be great

Thanks

Vince V.
  • 3,115
  • 3
  • 30
  • 45
  • According to https://stackoverflow.com/questions/9638247/is-jquery-browser-deprecated , $.browser is now deprecated, so the only answer that truly works is mijaved's: https://stackoverflow.com/a/39118730/7546203. The others will throw exceptions Unfortunately, currently I don't have enough points to comment on his answer. – Arquimaes May 03 '18 at 01:11

6 Answers6

47

I have had the same problem and is related with all Webkit based web browsers. If you set uppercase M the textbox show the moth with letters. The best solution for me was to override the validate date function from jquery.validate.js

Create jquery.validate.date.js and ensure it is loaded after jquery.validate.js

Add the following code to jquery.validate.date.js

$(function() {
    $.validator.methods.date = function (value, element) {
        if ($.browser.webkit) {

            //ES - Chrome does not use the locale when new Date objects instantiated:
            var d = new Date();

            return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
        }
        else {

            return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
        }
    };
});
Jan Saris
  • 403
  • 4
  • 7
user1011138
  • 644
  • 7
  • 12
  • 8
    new Date(d.toLocaleDateString(value)) will always be the current date and is not reflective of the value string. – Caleb Vear Nov 30 '11 at 07:53
  • That saved me hours of hassle :) – gls123 Jun 19 '12 at 08:13
  • Just remember $.browser has been deprecated and removed by JQuery 1.9 http://api.jquery.com/jQuery.browser/ – D.Rosado Jul 06 '13 at 11:32
  • 5
    This didn't work for me, toLocalDateString generating "Uncaught RangeError: Invalid language tag: 30/08/2013" – MarkB Aug 09 '13 at 14:20
  • the jquery.validate.js I have already had this code, and it doesn't work, same error that MarkB mentioned – bokkie Sep 04 '13 at 10:13
  • Using this function The client Side Validation have been desactivated – Chlebta May 08 '14 at 10:19
  • Got the same error that MarkB mentioned. I'm using the solution below instead – adelb Aug 26 '14 at 13:45
  • Since chrome prefers `d.toLocaleDateString(value)` and other browsers don't seem to mind it, you could get rid of the deprecated browser check and have the code always just execute the top block. – KyleMit Jan 21 '15 at 03:08
  • I am getting error `jquery.validate.min.js Uncaught TypeError: Cannot read property 'webkit' of undefined. Exception occurred when checking element DateOfBirth, check the 'date' method.` – Korayem Jun 11 '16 at 11:21
  • this question is about 5 years old and in chrome this still persists.. wonder why they don't fix.. – iamraviraj Aug 29 '16 at 16:51
  • This is working. But after I add annotation Remote Annotation at model view, this is failed again. I use UC Browser. I need to use Remote Annotation. IDK is it impact with the case or not. – toha Sep 29 '16 at 04:15
  • This fails normal validation on other fields so [here](http://stackoverflow.com/questions/12633471/mvc4-datatype-date-editorfor-wont-display-date-value-in-chrome-fine-in-interne) is the **working solution** , hope helps. – Shaiju T Oct 05 '16 at 10:24
26

user1011138 solution dont work for me since .toLocaleDateString(value) doesn't parse the value string

here's the solution i came up with => in jquery.validate.js find this function definition: "date: function (value, element)" and replace the code with:

// http://docs.jquery.com/Plugins/Validation/Methods/date
date: function (value, element) {
    var d = value.split("/");
    return this.optional(element) || !/Invalid|NaN/.test(new Date((/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) ? d[1] + "/" + d[0] + "/" + d[2] : value));
},
Chtioui Malek
  • 11,197
  • 1
  • 72
  • 69
  • 1
    Just be sure to adapt the array's format at the end of the line, but this is working for me, thank you – Sam Oct 08 '13 at 07:28
  • Got a question, how do I get it to validate 31 days an 12 months, and years? is it possible? – Gerardo Jaramillo Oct 24 '13 at 21:56
  • 1
    That solves the issue. Basically, the problem is releated with `chrome` and `chromiun`. The problem was identified with the jquery 1.8+. I think this is a provisional fix because, depends of the newest jquery update. Thanks @Chtiwi Malek – Benjamin RD Jan 21 '15 at 17:02
  • This also worked for me. Spent half of a day trying to find a solution in a "global" level – user2151486 Mar 22 '16 at 16:14
  • 1
    Thank you for your solution. I tried accepted answer but it was giving me invalid language error so I tried yours. it is working fine – Ubiquitous Developers Aug 31 '16 at 09:53
  • This is still not working. I use UC Browser. I need to use Remote Annotation. IDK is it impact with the case or not. – toha Sep 29 '16 at 04:14
5

The above solutions didn't work because jquery browser check is deprecated throwing jquery.validate.min.js Uncaught TypeError: Cannot read property 'webkit' of undefined. Exception occurred when checking element DateOfBirth, check the 'date'

In my project, I use momentjs with bootstrap datetimepicker, so this solution works great:

 $(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, 'DD/MM/YYYY').isValid();
  };
});

Call this right after loading jquery.validate()

Korayem
  • 12,108
  • 5
  • 69
  • 56
5

You've got to override default 'en-US' date validation with 'en-GB' date validation.

  • 'en-US' => 'mm/dd/yy'
  • 'en-GB' => 'dd/mm/yy'

Solution:

add a "jquery.validate.date.js" file in your project and put the following code in it:

//To Fix jQuery date format 'en-GB' validation problem in Chrome
$(function () {
    $.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 date in valid format [dd/mm/yyyy]"
    );
});

and make sure it load after the 'jquery.validate.min.js':

<script type="text/javascript" src="/Scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="/Scripts/jquery.validate.min.js"></script>
<script type="text/javascript" src="/Scripts/jquery.validate.date.js"></script>
mijaved
  • 671
  • 9
  • 11
4

Create a new jquery.validate.date.js file.

Paste the following code inside the file.

 $(function () {
    $.validator.methods.date = function (value, element) {
      if ($.browser.webkit) {
        var d = new Date();
        return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
      }
      else {
        return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
    }
  };
});

Now ensure that this file is loaded after jquery.validate.js file.

Milan
  • 3,005
  • 1
  • 24
  • 26
  • i am facing the exact problem and your script work well for me..but i am not sure what your script exactly do ? and does it have any limitations ? – John John May 23 '16 at 20:35
  • The code first of all checks for the browser. if condition is for chrome and else is for the rest of browsers. since Chrome does not use the locale when new Date objects instantiated, that's why .toLocaleDateString(value) is used for chrome and other browsers don't mind it. – Milan May 24 '16 at 05:03
  • Did you copy paste this solution written in 2011? http://stackoverflow.com/a/7878085/80434 – Korayem Jun 09 '16 at 23:05
  • @Korayem If i have copy/pasted the solution then i have not explained the answer as above.so chill – Milan Jun 10 '16 at 04:56
3
 $.validator.methods.date = function (value, element) {                
            if ($.browser.webkit) {                    
                var d = value.split("/");   
                return this.optional(element) || !/Invalid|NaN/.test(new Date((/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) ? d[1] + "/" + d[0] + "/" + d[2] : value));
              }
            else {
                return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
            }
        };
Nayan Hodar
  • 508
  • 7
  • 12
  • Thnx Chtiwi Malek for your code. This code work for me in chrome and firefox. – Nayan Hodar Nov 28 '15 at 06:33
  • 4
    I am getting error `jquery.validate.min.js Uncaught TypeError: Cannot read property 'webkit' of undefined. Exception occurred when checking element DateOfBirth, check the 'date' method.` – Korayem Jun 11 '16 at 11:21