Solution 1 :

According to MDN:

For maxLength

Valid for text, search, url, tel, email, and password, it defines the maximum number >of characters (as UTF-16 code units) the user can enter into the field. This must be >an integer value 0 or higher. If no maxlength is specified, or an invalid value is >specified, the field has no maximum length. This value must also be greater than or >equal to the value of minlength.

So type=number is ignored. Here is a work around using the pattern

<input type="text" pattern="d*" maxlength="4">

Solution 2 :

<!DOCTYPE html>
<html>

<body>

  <h2>JavaScript Validation</h2>

  <p>Enter a number and click OK:</p>

  <input id="id1" type="number" min="100" max="300" required>
  <button onclick="myFunction()">OK</button>

  <p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>

  <p id="demo"></p>

  <script>
    function myFunction() {
      const inpObj = document.getElementById("id1");
      if (!inpObj.checkValidity()) {
        document.getElementById("demo").innerHTML = inpObj.validationMessage;
      } else {
        document.getElementById("demo").innerHTML = "Input OK";
      }
    }
  </script>

</body>

</html>

Problem :

How to set the max-length value in input tag when type is number?

<html>
<body>
<input type="number" maxlength="10">
</body>
</html>

Comments

Comment posted by Community

Please provide additional details in your answer. As it’s currently written, it’s hard to understand your solution.

By