HTMLelement.min and HTMLelement.max properties are not working

Viewed 17

I want the user to be able to input numbers in the range of 1-12 in a dynamically created input element:

let input = document.createElement("input");
input.type = "number";
input.min="1";
input.max="12";
input.style.width="80px";
input.style.textAlign="center";
document.body.appendChild(input);

But after you run this snippet you can see that the user can enter any number. How do I fix this?

1 Answers

Specifying minimum and maximum values You can use the min and max attributes to specify a minimum and maximum value that the field can have. For example, let's give our example a minimum of 0, and a maximum of 100:

<input type="number" placeholder="multiple of 10" step="10" min="0" max="100" />

In this updated version, you should find that the up and down step buttons will not allow you to go below 0 or above 100. You can still manually enter a number outside these bounds, but it will be considered invalid.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input/number

You can use the onBlur method to validate the user's input

<input type="text" oninput="limiteValue(this)" onpropertychange="limiteValue(this)" />

  function limiteValue(obj) {
    obj.value = obj.value.replace(/[^\d]/g, '');
    if (obj.value > 12) {
      obj.value = 12;
    }
    if (obj.value < 1) {
      value = 1;
    }
    if (obj.value.length > 2) {
      obj.value = obj.value.slice(0, 2);
    }
    if (obj.value.substr(0, 1) == '0' && obj.value.length == 2) {
      obj.value = obj.value.substr(1, obj.value.length);
    }
  }
Related