Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML how to stop users from typing dates larger than 2100-01-01?

I have the following input field:

<input type="date" min="2020-11-04" max="2100-01-01"/>

This works perfectly fine to restrict dates from 2020-11-04 till 2100-01-01 in the date picker. However, it's still possible for the user to enter a date larger or smaller than the specified min and max by typing in the input field.

Is there a way I can prevent this client-side using HTML and/or with JavaScript, so the user can't type in a date larger or smaller than the specified min and max? I would like to keep the date picker that comes with <input type="date">, so I'm unsure if using a regex pattern would be the right way to go about this.

like image 789
Drago Avatar asked Dec 15 '25 07:12

Drago


2 Answers

You can "prevent" the keydown events in the input field. That would force the user to use the date picker.

Here I added a class to the input and used querySelectorAll in case you have more than one field to affect.

While I quite agree with @gavgriff about his advice to validate fields... Your question was "How to stop users from typing" ;)

document.querySelectorAll(".noTyping").forEach(el=>{
  el.addEventListener("keydown", function(e){
    e.preventDefault()
  })
})
<input class="noTyping" type="date" min="2020-11-04" max="2100-01-01"/>
like image 170
Louys Patrice Bessette Avatar answered Dec 16 '25 20:12

Louys Patrice Bessette


I have written this simple working script to make a smooth date typer which is going to fix your problem and gives a better experience. You can try and use the up/down arrows on your keyboard to see how it works when the picked date is higher/less than the conditions.

const customDateLimiter = input => {
  let conditionDates = {
    min: new Date(input.min),
    max: new Date(input.max)
  }
  const currentDate = new Date(input.value);

  if( currentDate < conditionDates.min ) 
    input.value = conditionDates.min.toLocaleDateString().replaceAll("/", "-").split("-").reverse().join("-").toString();
  //console.log(  currentDate < conditionDates.min );
  
  if( currentDate > conditionDates.max ) 
    input.value = conditionDates.max.toLocaleDateString().replaceAll("/", "-").split("-").reverse().join("-").toString();
  //console.log(  currentDate > conditionDates.max );
  
  return input.value;
}
<input type="date" min="2020-11-04" max="2100-01-01" onchange="customDateLimiter(this)" />
like image 45
Adnane Ar Avatar answered Dec 16 '25 20:12

Adnane Ar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!