In this article we will see how to dynamically create a range for a date input field with JavaScript.
The date input has the min and max attributes which are used to set the minimum and maximum date for a date selection. These attributes must both have a string value in a valid date format (for example YYYY-mm-dd).
We can then implement the following solution:
'use strict';
const formatDate = date => {
return date.toISOString().split('T')[0]; // YYYY-mm-dd
};
const setDateRange = (inputElement, startDate, endDate) => {
inputElement.setAttribute('min', formatDate(startDate));
inputElement.setAttribute('max', formatDate(endDate));
};
const inputDate = document.getElementById('date');
const now = new Date();
const year = now.getFullYear();
const nextMonth = now.getMonth() + 1;
const nextDay = now.getDate();
setDateRange(inputDate, now, new Date(year, nextMonth, nextDay));
In this example we have narrowed the date selection from the current day down to one month in the future. The formatDate() function makes use of the ISO format to convert a Date object to the YYYY-mm-dd format so that we can use it with the min and max attributes.