maxlength ignored for input type="number" in Chrome
Solution 1:
From MDN's documentation for <input>
If the value of the type attribute is
text
,search
,password
,tel
, orurl
, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.
So maxlength
is ignored on <input type="number">
by design.
Depending on your needs, you can use the min
and max
attributes as inon suggested in his/her answer (NB: this will only define a constrained range, not the actual character length of the value, though -9999 to 9999 will cover all 0-4 digit numbers), or you can use a regular text input and enforce validation on the field with the new pattern
attribute:
<input type="text" pattern="\d*" maxlength="4">
Solution 2:
Max length will not work with <input type="number"
the best way i know is to use oninput
event to limit the maxlength. Please see the below code.
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>