Click here to Skip to main content
15,881,092 members
Articles / Web Development / HTML
Tip/Trick

Fixing jQuery non-US Date Validation for Chrome

Rate me:
Please Sign up or sign in to vote.
4.81/5 (8 votes)
13 May 2013CPOL2 min read 54.4K   388   4   6
How to fix date validation for non-US date when using Chrome

Introduction

When using jQuery validation for dates, you will find out that it does not work well for dates using Chrome. This happens when you use a non-US locale.

This tip will provide an example displaying the bug, and another one showing its fix. Both codes are available for download. The one holding the problem is the date_with_bug.html, and one displaying the solution is the date_fixed.html.

Background

This tip is based on the solution presented in the following link: jQuery Date Validation in Chrome. According to this tip, Chrome does not take into account localization when processing dates. The solution presented in the mentioned link, however, does not work when the Operating System is setup to use a non-US locale. This tip does take this into consideration providing the correct solution for all scenarios.

Using the Code

Please do remember that to reproduce the issues in this tip, your Operating System has to be configured to a US-locale.

Displayed below is the code which illustrates the problem. Note that this is a simple form holding an input and a submit button. In the input, the jQuery calendar is attached. Finally observe, as well, that the date input is being validated for the requirements of a mandatory field and a date one.

HTML
<!doctype html>
 
<html>
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" 
  href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
  <script src="./jquery.validate.min.js"></script>
  <script src="./jquery.ui.datepicker-pt-BR.js"></script>
  <link rel="stylesheet" 
  href="http://www.codeproject.com/resources/demos/style.css" />
  <script>
    $().ready(function() {
        
        $.datepicker.setDefaults($.datepicker.regional["pt-BR"]);
    
        $( "#datepicker" ).datepicker();
      
        // validate date form 
        $("#dateForm").validate({
            rules: {
                datepicker: {
                    required: true,
                    date: true
                }
            }
        });
    });
  </script>
</head>
<body>
    <form id="dateForm">
        <p>Date: <input type="text" 
        id="datepicker" name="datepicker" /></p>
        <p><input type="submit" /></p>
    <form>
</body>
</html>  

If you open the chrome browser with this source code (leave the JavaScript files in the zipped file where they were so everything works properly) and select the date April, 17, 2013 via jQuery calendar, you will note that the date will be printed as "17/04/2013" which is the pt-br date format, which is the locale setup. Now, try to submit the form by pressing "Submit Query". You will see a message stating the date is invalid.

In order to solve this issue, you should extend jQuery functionality and force date localization for the chrome browser only, as displayed below:

JavaScript
// fix date validation for chrome
        jQuery.extend(jQuery.validator.methods, {
            date: function (value, element) {
                var isChrome = window.chrome;
                // make correction for chrome
                if (isChrome) {
                    var d = new Date();
                    return this.optional(element) || 
                    !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
                }
                // leave default behavior
                else {
                    return this.optional(element) || 
                    !/Invalid|NaN/.test(new Date(value));
                }
            }
        }); 

Adding the code above to the HTML example used in the tutorial, you will have the code displayed below:

HTML
<!doctype html>
 
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" 
  href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
  <script src="./jquery.validate.min.js"></script>
  <script src="./jquery.ui.datepicker-pt-BR.js"></script>
  <link rel="stylesheet" 
  href="http://www.codeproject.com/resources/demos/style.css" />
  <script>
    $().ready(function() {
        
        // fix date validation for chrome
        jQuery.extend(jQuery.validator.methods, {
            date: function (value, element) {
                var isChrome = window.chrome;
                // make correction for chrome
                if (isChrome) {
                    var d = new Date();
                    return this.optional(element) || 
                    !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
                }
                // leave default behavior
                else {
                    return this.optional(element) || 
                    !/Invalid|NaN/.test(new Date(value));
                }
            }
        });
        
        // set default date for pt-br
        $.datepicker.setDefaults($.datepicker.regional["pt-BR"]);
    
        // setup date picker
        $( "#datepicker" ).datepicker();
      
        // validate date form 
        $("#dateForm").validate({
            rules: {
                datepicker: {
                    required: true,
                    date: true
                }
            }
        });
    });
  </script>
</head>
<body>
    <form id="dateForm">
        <p>Date: <input type="text" 
        id="datepicker" name="datepicker" /></p>
        <p><input type="submit" /></p>
    <form>
</body>
</html> 

If you execute the code above selecting again April 17, 2013 and submit the form, you will see that the validation passed as it should have.

Points of Interest

The interesting part of this tip was that the fixing did not involve changing the jQuery source script itself, but extending it. Doing this makes the solution pluggable and much easier to maintain.

History

  • Version 1.0: Added initial version of the tip
  • Version 2.0: Added fix for the case where the Operating System is configured to a non-US locale

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Brazil Brazil
Graduated from Universidade Estadual de Campinas (State University of Campinas - UNICAMP) having experience with undergrad research.

Started working as a developer with Java and .NET Web and Desktop applications. Also, developed Eclipse PDE, Perl, PHP and Android applications.

Currently working as a Tech Lead, Architect and ScrumMaster for .NET and Java Enterprise applications.

Main interests: Software Architecture, Technical Leadership, Web and Mobile applications, SCRUM

Comments and Discussions

 
GeneralMy vote of 2 Pin
rohitiscancerian8-Nov-15 23:46
rohitiscancerian8-Nov-15 23:46 
GeneralRe: My vote of 2 Pin
Eduardo Antonio Cecilio Fernandes10-Nov-15 23:09
Eduardo Antonio Cecilio Fernandes10-Nov-15 23:09 
GeneralRe: My vote of 2 Pin
rohitiscancerian10-Nov-15 23:13
rohitiscancerian10-Nov-15 23:13 
GeneralRe: My vote of 2 Pin
Eduardo Antonio Cecilio Fernandes10-Nov-15 23:24
Eduardo Antonio Cecilio Fernandes10-Nov-15 23:24 
QuestionWhat is it that this is supposed to do? Pin
nptomlin24-Jun-13 5:00
nptomlin24-Jun-13 5:00 
AnswerRe: What is it that this is supposed to do? Pin
Eduardo Antonio Cecilio Fernandes25-Jun-13 0:57
Eduardo Antonio Cecilio Fernandes25-Jun-13 0:57 
Hello,

Well, in theory you would not need thetoLocaleDateString(value) method. However, the chrome has a bug which it does internationalize the date automatically, so this must be done manually. I´m not sure I answered your question though... is it what you wanted to know?

Regards,

Eduardo

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.