Click here to Skip to main content
Click here to Skip to main content

Fixing jQuery non-US date validation for Chrome

By , 18 Apr 2013
 

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 article 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 article, Chrome does not take into account localization when processing dates.

Using the Code

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.

<!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 as displayed below:

// fix date validation for chrome
jQuery.extend(jQuery.validator.methods, {
    date: function (value, element) {
        // original version return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
        // correction for chrome bug of locale
        var d = new Date();
        return this.optional(element) || 
		!/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
    }
});

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

<!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() {
        
        // fix date validation for chrome
        jQuery.extend(jQuery.validator.methods, {
            date: function (value, element) {
                // original version return this.optional(element) || 
                // !/Invalid|NaN/.test(new Date(value));
                // correction for chrome bug of locale
                var d = new Date();
                return this.optional(element) || 
                	!/Invalid|NaN/.test(new Date(d.toLocaleDateString(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.

License

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

About the Author

Eduardo Antonio Cecilio Fernandes
Architect
Brazil Brazil
Member
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 an Architect and ScrumMaster for .NET and Java Enterprise applications.
 
Main interests: Software Architecture, Technical Leadership, Web and Mobile applications, SCRUM

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130513.1 | Last Updated 18 Apr 2013
Article Copyright 2013 by Eduardo Antonio Cecilio Fernandes
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid