javascripthtmldaterestriction

HTML & JS - input type=date - Trying to configure input type date to restrict the user from selecting days after, or more than 90 before current date


I'm working on a project that requires the user to select a date, which will then return a list of times for that specific date, but I need to restrict the user from selecting any days that haven't occurred yet, or that are more than 90 days in the past.

I'm trying to do this just with HTML, plain Javascript and CSS, but so far almost everything I've found has been using Jquery.

HTML

<div id="dateSelector">
    <input type="date" id="datePicker"></input>
</div>

I know it's possible to set min and max dates, but I haven't been able to find a way to set these limits dynamically to update every day so that the furthest date available is always 90 days away.

I have tried something similar to:

<input type="date" name="date" id="datePicker" min="<?=date('Y-m-d', strtotime('-90 days')) ?>">

but had no luck with the results (no dates were disabled or restricted).


Solution

  • You can do it with Javascript :

    const input = document.getElementById('datePicker');
    
    const min = new Date();
    min.setDate(min.getDay() - 90);
    const minStr = min.toISOString();
    input.min = minStr.substring(0,minStr.indexOf('T'));
    <input type="date" name="date" id="datePicker">