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="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Then the JavaScript code itself is like as follows:

<script>
$( function() {
$( "#datepicker" ).datepicker({ minDate: -20, maxDate: "+1M +15D" });
} );
</script>

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: https://www.w3schools.com/code/tryit.asp?filename=FTUTR9BYRNI0

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: https://www.w3schools.com/code/tryit.asp?filename=FTUU7AU8HAT3

Often times we need to select a range of dates, such as a begin data and an end date, and this kind of scenario is commonly seen on websites such as hotel, car rental, and airline companies. To implement this, we need to make sure the following requirements will be met:

  1. Valid date format for both begin date and end date
  2. The begin date must be earlier than the end date

The first requirement is easy to implement, but the second one is a little bit tricky. Since we cannot force user to enter the begin date before the end date, we must trigger a validation whenever a date is entered in either the begin date textbox or the end date textbox.

The official website of jQuery Datepicker has a good example of the date range: https://jqueryui.com/datepicker/#date-range

Let’s take a look at the code to understand how it works.




HTML code:

<label for="from">From
<input id="from" name="from" type="text" />
<label for="to">to
<input id="to" name="to" type="text" />

The JavaScript code looks like this:

<script>
$( function() {
var dateFormat = "mm/dd/yy",
beginDate = $( "#from" )
.datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
.on( "change", function() {
endDate.datepicker( "option", "minDate", getDate( this ) );
}),
endDate = $( "#to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
.on( "change", function() {
beginDate.datepicker( "option", "maxDate", getDate( this ) );
});


function getDate( element ) {
var date;
try {
date = $.datepicker.parseDate( dateFormat, element.value );
} catch( error ) {
date = null;
}
return date;
}
} );

The important part of the code is this line of code:

.on( "change", function() {
endDate.datepicker( "option", "minDate", getDate( this ) );
}),

It says that when there is a change in the “from” field (represented by variable beginDate), the value in the “from” field will be parsed as a Date object (parsed by the function getDate) and be passed to the “to” field (represented by variable endDate) as the minimum selectable date (minDate), so when user tries to enter the date in the “to” textbox, the earliest selectable date will be the date entered in the “from” field.

Likewise, this line of code:

.on( "change", function() {
beginDate.datepicker( "option", "maxDate", getDate( this ) );
})
will parse the date in the “to” field by the getDate function and pass it to the “from” field (represented by beginDate) as the maximum select date.

This implementation works well until an invalid date is directly entered in any of the textboxes, such as “02/30/2018”, because Datepicker does not validate the data entered in the textbox and will pass the data for parsing.

Leave a Reply

avatar
  Subscribe  
Notify of