'How can I restrict a time input value?

I want to display an input type hour from 08:00 to 20:00. I tried this:

<input type="time" id="timeAppointment" name = "timeAppointment" min="08:00" max="20:00" placeholder="hour"  required/>

But when I display it I can still select any time, it does not restrict me as I indicate. What is the problem? If is necessary some code I work with Javascript.



Solution 1:[1]

Setting min and max properties in input tags do not inherently prevent you from accepting out of range values as inputs, but it controls the valid property of the tag, which can then be used such as in css to style your page accordingly. Some browsers do make it so that you cannot input out of the specified range, but it is not platform-independent behaviour.

See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time#setting_maximum_and_minimum_times

If you want to ensure that only the time between min and max are input, you could programmatically implement that using an onchange listener on your input element as follows:

Make sure to indicate to the user why their input is not changing (because it is not between min and max) using css and text, etc.

const timeInput = document.getElementById("timeAppointment");
timeInput.value = '15:56';

let previousValue = timeInput.value;

timeInput.onchange = () => {
  console.log(previousValue)
  console.log(timeInput.value)
  
  if (timeInput.value < timeInput.min || timeInput.value > timeInput.max) {
    timeInput.value = previousValue;
  }
  
  previousValue = timeInput.value;
}
<input type="time" id="timeAppointment" name="timeAppointment" min="08:00" max="20:00" required/>

However, there is a caveat to this. Imagine you are changing your time from 02:00PM to 11:00AM. You would go from left to right, and as soon as you change 02 hours to 11 hours, the javascript validation fails as it becomes 11:00PM and the value is not able to update.

Either you will have to write a convoluted way to get around all the edge cases, or the users will have to find a weird way to change their time. This is why this is generally a bad idea to validate on every input like this, and instead you can validate it when you submit the form, or onfocusout and let the user know by appropriate styling.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1