To limit the number of characters that can be added to an HTML <input>
element, you can add the following attributes on it (as per your need):
minlength
— to set the lower-bound limit on number of characters the user can add;maxlength
— to set the upper-bound limit on number of characters the user can add.
Both, minlength
and maxlength
attributes, are very well-supported across different browsers.
For example, to limit an <input>
element to a minimum of 3
and a maximum of 10
characters, you would do the following:
<input type="text" minlength="3" maxlength="10" />
This would make the user input invalid if it's less than 3
characters long, and it would not allow the user to input more than 10
characters (specific implementation may vary in different browsers, but the general idea remains the same).
To be specific, the limit on characters is based on the number of UTF-16 code units that can be added to the <input>
element.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.