When creating a date picker, I have it set to only allow today onwards. which works... But it appears that the user can then tab into the field and change the date to "before" today. Is there a way to enforce the "must be today or future date" rule?
Here is my example;
var today = new Date();
var d = today.getDate();
var m = today.getMonth() 1;
var y = today.getFullYear();
if (d < 10) {
d = '0' d
}
if (m < 10) {
m = '0' m
}
today = y '-' m '-' d;
document.getElementById("datePicker").setAttribute("min", today);
<input id="datePicker" type='date' >
CodePudding user response:
use EventListener to listen and set the value of your input to today date when entered value is lower than today
var today = new Date();
var d = today.getDate();
var m = today.getMonth() 1;
var y = today.getFullYear();
if (d < 10) {
d = '0' d
}
if (m < 10) {
m = '0' m
}
today = y '-' m '-' d;
const input = document.getElementById("datePicker")
input.setAttribute("min", today);
input.addEventListener('change', (event) => {
const d1 = new Date(today);
const d2 = new Date(event.target.value);
if(d1.getTime() > d2.getTime()){
event.target.value = today
}
});
<input id="datePicker" type='date'>