How to Validate Date when Using jQuery Datepicker

It is a common practice to use some calendar tool for date entry in a web application because it is user friendly and can enforce the format of the entered date to the way you want it to, for example, jQuery Datepicker. But it is also important that user can manually enter a date if they choose not to use the calendar tool or when it is easier to manually enter the date than using the tool, for example, it takes more time to locate “07/18/1988″ using a calendar tool than manually entering it. As web developer, we know that flexibility and convenience of an application always come with a price tag, and in this case, there must be some validation and sanitization of the date that user manually entered. Remember the basic principle regarding user input: All user input is evil, and it is your job to validate and sanitize the user input to protect your application’s integrity and security. So today I will show you how to validate a date when using the jQuery Datepicker for date entry.

Note: I am in US so I will use mm/dd/yyyy date format in this tutorial.

Now let’s start with the simplest scenario which has only one date entry textbox.

HTML code:

<h2>Date Validation Using jQuery Datepicker</h2>
<p>Date: <input type=”text” id=”datepicker”></p>

JavaScript code:

We first need to add links to jQuery and jQueryUI library:

<link rel=”stylesheet” href=””>
<script src=””></script>
<script src=””></script>

Then the JavaScript code itself is like as follows:

$( function() {
$( “#datepicker” ).datepicker({ minDate: -20, maxDate: “+1M +15D” });
} );

In the code above, ‘minDate: -20′ means the earliest date that a user is able to select is 20 days before today’s date. For example, if today’s date is 08/01/2018, then the earliest selectable date will be “07/12/2018”. ‘maxDate: “+1M +15D”‘ means that the latest selectable date will be one month (“M” for months) and 15 days (“D” for days) after today’s date. So if today is 08/01/2018, then the latest selectable date will be “09/16/2018”. You can try this simple code from this link:

Now let’s see how we can improve this JavaScript code. Say we need to loosen the date range to “3 months and 15 days before and after today’s date”, so we can change the above code to {minDate: “-3M -15D”, maxDate: “+3M +15D”}. However, if the user needs to select a date three months before today, then he/she has to click the calendar left arrow three times to change the month; this is not a good design from the user’s perspective and a better design is to have a month dropdownlist so user can select the month more quickly. This can be done by adding changeMonth (similarly, changeYear) to the datepicker’s options: { minDate: “-3M -15D”, maxDate: “+3M +15D”,changeMonth:true,changeYear:true }. You can try this code from this link:




Leave a Reply

Notify of