How can I set max-length in an HTML5 "input type=number" element?
You can set a maxlength on an input type="number"
by harnessing the power of JavaScript to restrict the input length. This is how you do it:
Heads up!: Swap the 5
with your chosen maximum number of digits. This code snippet effectively results in a number restricted to a 5-digit maximum while the user types.
Exploring the restrictions of input type=number
Fundamentally, the <input type="number">
element does not inherently support the maxlength attribute for a handful of reasons including:
- It's used primarily for numeric entries, and the idea is to maximize value, not length.
- Length of numeric entries vary owing to factors like decimals and negatives.
However, in the real world, developers need to control length for proper data validation and improved user experience.
Triggering JavaScript events for maxlength
You can leverage JavaScript events, such as oninput
and onkeyup
, to enforce a specific character length. For instance:
And don't forget to add maxLength
programmatically:
This ensures the user's input maintains the limit as they type.
Alternative inputs and patterns
Facing validation complexities with type="number"
? You can switch to alternatives that respect length restrictions:
<input type="tel">
comes with native maxlength support, while also displaying a number pad on mobile.<input pattern="[0-9]{5}">
restricts the pattern to a 5-digit numeric input.
Both options retain the usability of numeric input with less fuss.
Using custom validation messages for input values
Informative feedback is integral when users exceed the maxlength:
With this snippet, users receive immediate guidance if they surpass the limit, enhancing their experience.
Handling form submission and exceeding max
When handling form submissions, stop the default action and validate the input using JavaScript if it exceeds max
:
This step ensures data integrity before it reaches your server.
Getting to grips with spinner buttons
When you use type number, spinner buttons can provide a good preview of the allowed range. They let users increment values without exceeding the specified max
:
With the above <input>
element, users can adjust values within 1 to 99999 using the up/down arrows (no more, no less).
Was this article helpful?