Datepicker Validation is not working on using jquery plugin


I'm having scenario like choosing/entering of date from datepicker. I have used jquery plugin for datepicker. It worked perfectly.

As I said earlier, user also having an advantage of entering date directly in textbox instead of choosing from calendar. At this stage, as we all know that the user may happen to enter the date wrongly. Hence I stepped in jquery datepicker validation plugin. There I found some articles to proceed.

The useful links are as follows,

<a href="http://keith-wood.name/uidatepickervalidation.html" rel="nofollow">keithwood</a>

<a href="http://jsfiddle.net/99u5ahb0/" rel="nofollow">Jsfiddle</a>

<a href="https://stackoverflow.com/questions/13819135/jquery-date-picker-validation-problems/13819594?noredirect=1#comment48428483_13819594" rel="nofollow">Chridam says</a>

<strong>What I tried is:</strong>

As first link says(Keith wood), I tried with datepicker.validation.js. But nothing happens when i enter the wrong date. Below is the complete code which I tried,

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta charset="UTF-8"> <title> Test for date picker</title> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/south-street/jquery-ui.css"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script> <script type="text/javascript" src="jquery.validate.js"></script> <script type="text/javascript" src="jquery.ui.datepicker.validation.js"></script> <script src="demo.js" type="text/javascript"></script> </head> <body> <form id="validateForm" action="#"> <script > $('#validateForm').validate({ errorPlacement: $.datepicker.errorPlacement, rules: { validDefaultDatepicker: { required: true, dpDate: true }, validBeforeDatepicker: { dpCompareDate: ['before', '#validAfterDatepicker'] }, validAfterDatepicker: { dpCompareDate: { after: '#validBeforeDatepicker' } }, validTodayDatepicker: { dpCompareDate: 'ne today' }, validSpecificDatepicker: { dpCompareDate: 'notBefore 01/01/2012' } }, messages: { validFormatDatepicker: 'Please enter a valid date (yyyy-mm-dd)', validRangeDatepicker: 'Please enter a valid date range', validMultiDatepicker: 'Please enter at most three valid dates', validAfterDatepicker: 'Please enter a date after the previous value' } }); </script>

Select Date: <input type="text" size="10" name="validDefaultDatepicker" id="validDefaultDatepicker"/>

<script> $(function () { $('#validDefaultDatepicker').datepicker(); }); </script> </form>

As per the second link(chridam), I tried with type = date concept directly. It gave me hope as it worked perfectly. Though the solution is nice, it is not working IE browsers. Below is the complete code,

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script> <script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script> <script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script> <script type="text/javascript"> $(function () { $("#jQueryValidateTest").validate(); $("[type=date]").datepicker({ onClose: function () { $(this).valid(); } }); }); </script> <style> .valid { background: green; color: #fff; } .error { background: red; color: #fff; } </style> </head> <body> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <form id="jQueryValidateTest"> <input type="date" required> </form>​ </td> </tr> </table> </body> </html>

Hope I'm not confusing you. Kindly help me to overcome this hurdle. Thanks in advance.


If I understand your question completely you'd like to have custom input validation for dates. It's a problem I recently had for a flight booking website (<a href="http://www.connections.be/en" rel="nofollow">live ex.</a>)

One thing for sure is that input fields of type date are nice, but not very x-browser because they roll out with they're own date format, depending on the device/OS/browser culture. So my solution is for text input types. It also uses jquery UI datepicker and unobtrusive validation plugin.

To conquer this hurdle one big advantage that IS inside jQuery UI datepicker, apart from the missing manual input validation, is the option <a href="https://api.jqueryui.com/datepicker/#option-constrainInput" rel="nofollow">constrainInput</a> which allows only the characters by it's current format. That's already a big win!

On a second note jQuery UI also comes with culture files to instantiate datepickers against a custom format.

Building on top of that, I believe a custom validation method is required. Then one big difference compared to your setup might be the use of minDate & maxDate options. Not sure if that's applicable to you but that's how I got it to validate correctly.

/** * @description resolves an issue with chrome & safari date validation * @param {String} format : regional dateformat */ setValidator: function (format) { var self = this, // scope settings = this.settings, // object literal data = settings.data, // mapping for data-attributes options = settings.options; // my custom behavior options $.validator.addMethod('date', function (value, element) { var inst, // jquery ui datepicker data inst object => very handy parts, // split the user input minDate = new Date(), // create a min range maxDate = new Date(minDate), // create a max range newDate; // the date to be validated in the end // unrequired fields if (this.optional(element)) { return true; } try { // get the data instance from the element, put there by jquery-ui // warning: inline datepickers have their instance on the resp. div inst = options.isInline ? self.findDatepicker($(element)).data(data.datepicker) : $(element).data(data.datepicker); // determine the epoch timestamps of the input, based on the options minDate and maxDate, for calculation minDate = typeof inst.settings.minDate === 'object' ? inst.settings.minDate.getTime() : minDate.setDate(minDate.getDate() + parseInt(inst.settings.minDate.replace(/[+d]/g, ''), 10)); maxDate = maxDate.setDate(maxDate.getDate() + parseInt(inst.settings.maxDate.replace(/[+d]/g, ''), 10)); // correct months 0-based // correct 2digit years // add hours to the maxDate parts = value.split('/'); if (parts.length === 3) { parts[0] = parseInt(parts[0], 10); parts[1] = parseInt(parts[1], 10) - 1; parts[2] = parseInt(parts[2], 10) < 100 ? parseInt(parts[2], 10) + 2000 : parseInt(parts[2], 10); // notice how I switch the parts against the default format newDate = new Date(parts[2], parts[1], parts[0], 23, 59, 59, 0).getTime(); if ($(element).data(data.maxdate)) { newDate = newDate - (new Date(newDate).getHours() * 60 * 60 * 1000); } // unfortunately not very usefull as it doesn't return anything when false => value.split('/') //$.datepicker.parseDate(format, value); } else { newDate = 0; } return newDate >= minDate && newDate <= maxDate; } catch (err) { console.log(err); } }); }

Basically I loop over every jQuery datepicker:

<ul><li>get/set the culture from i18n culture files with ajax => '/scripts/lib/jquery-ui/ui/i18n/datepicker-{{culture}}.js'</li> <li>set the validator with the format param => self.setValidator(regional.dateFormat);</li> <li>set the options for datepicker => $('.datepicker').datepicker(options);</li> </ul>

Hope that makes sense a bit or at least push you in the right direction. If something is unclear, ask away ... as I realize this is not a copy/paste solution ^^


  • Difference between two particular dates [duplicate]
  • PHP Carbon “month()” method generates wrong DateTime
  • html5 tag support
  • How to use java.time.LocalDate on a Play Framework JSON Rest?
  • Year, Month, and Day parameters describe an un-representable DateTime in Persian calender
  • jQuery - how to validate a date of birth using jQuery Validation plugin?
  • Visual Studio 2010 - 2015 does not use ymm* registers for AVX optimization
  • jQuery random blockquote
  • A simple datepicker in VueJS
  • How to make Plotly chart with year mapped to line color and months on x-axis
  • How to parsing NSDate to RFC 822 always use in English?
  • iOS Date formatting
  • stop execution in Custom validator if it false
  • Get localized short date pattern as String?
  • Trying to string.Join an IList
  • HTML5 video only works in IE. The other browsers shows the black screen
  • MeeGo Handset Emulator not starting on Windows 7
  • C++ friend class std::vector
  • Knockout custom binding handler
  • Using $compile in a directive triggers AngularJS infinite digest error
  • How to make Twilio api Post request with the help of AFNetworking?
  • Unable to send e-mail through Java
  • didUpdatePushCredentials not get called
  • UIAlertController button function not working
  • Symfony 2. CSRF token is invalid
  • SetWindowsHookEx does not react on media keys
  • Element.tagName for python not working
  • Graphics.CopyFromScreen [Web application] + The handle is invalid
  • How solve “Qt: Untested Windows version 10.0 detected!”
  • Unable to decode certificate at client new X509Certificate2()
  • Parse a date string in a specific locale (not timezone!)
  • Install PHP intl extension on MacOS
  • Retrieve list of sent friend requests from friend_request FQL table
  • NHibernate Validation Localization with S#arp Architecture
  • How can I send an e-mail from a vbs script
  • Accessing IRQ description array within a module and displaying action names
  • Apache 2.4 and php-fpm does not trigger apache http basic auth for php pages
  • Release, debug version and Authorization Google?
  • Is there a mandatory requirement to switch app.yaml?
  • Getting Messege Twice Using IMvxMessenger