skip to Main Content

I wonder why default maxLength/minLength property for HTMLInputElement is set to -1 by default.

There is also confusing behavior like below:

  1. Example
<input type="text" />
const inputElement = document.querySelector('input');
console.log(inputElement.maxLength) // -1

  1. I set maxLength programatically
inputElement.maxLength = 2;
console.log(inputElement.maxLength) // 2

and html will reflect as

<input type="text" maxlength="2" />

  1. I remove maxlength="2" manually from devtools.
<input type="text" />

I get

console.log(inputElement.maxLength) // undefined

can someone tell me why is that? There is no such a thing in documentation, but i can see that every browser is pretty consistent in this.

[Edit] 3. is wrong in this example, it is return -1 https://stackoverflow.com/a/75541575/10465908

3

Answers


  1. Chosen as BEST ANSWER

    So answer to my original question is https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#limited-to-only-non-negative-numbers as maxLength is type long.

    But I discovered some interesting things during the investigation:

    1. WebKit returns -1 but real maxlength is 524288, other engines seems not have this limitation.
    2. It was 524288 in other browsers way back
    3. During IDL attributes spec, they all decided to return -1

  2. Insightful question.

    Well, according to the official docs of the Web, the World Wide Web,

    The default value for this attribute is an unlimited number

    And as we all know computers cannot represent infinity.

    A big number (like 1 billion) is big but still not infinity or "unlimited". So the best way was to choose a negative number (-1). Just in this way, they are not setting a max length constraint on the input.

    However, please note that they decided to do it just from their side (to do this workaround) i.e. we cannot set explicitly the -1. For example:

    enter image description here

    Login or Signup to reply.
  3. For the step 3 i’m getting -1 when i remove attribute in chrome 110

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search