Search code examples
htmldateinputattributesmin

HTML5 input's "min" attribute is not graying out calendar's past dates


I know it's a fairly common and repetitive question but I haven't found a solution nor a explicit reason why this is happening and I'm getting frustrated with something so simple yet important.

I have a form with an <input type=date /> whose min attribute varies depending on the current date. I have this JS routine to determine the current date and then modify the input type=date

let today = new Date();
let day = today.getDate();
let month = today.getMonth()+1;
let year = today.getFullYear();

today = year + '-' + month + '-' + day;

console.log(today)

const calendarInput = document.getElementById('to-do-date');
calendarInput.min = today;

When I check Chrome's Elements Console, my input tag looks like this

<input type="date" id="to-do-date" name="to-do-date" min="2020-8-31" required> <!-- That's date that I'm writing this-->

Pretty straight-forward, right?

But when I go to my form for the actual date input on my form, I get this

Input's calendar not graying out previous dates

In the image, you can see that my calendar is not graying out the dates previous to my min attribute which is, as today, 2020-08-31, even though I explicitly stated to take today's date and put it as a min attribute and I have used different validation methods to prevent users from entering past dates but to no avail.

If you guys know the reason behind this and share it, I will truly appreciate it.

Thanks


Solution

  • This is happening because you need to have "yyyy-mm-dd" format, but now you have "yyyy-m-d" format. So you need to add a little function, which will correct your date:

    const correctDate = (date) => date < 10 ? '0' + date : date;
    
    today = year + '-' + correctDate(month) + '-' + correctDate(day);
    

    I hope, this will help you!