Limit number of characters allowed in form input text field
To restrict the number of characters in an input field, use the maxlength attribute in the input tag:
This restricts users to 10 characters, as simple as that.
JavaScript intervention for more precision
Sometimes, a pinch of JavaScript can give you more control over the user inputs. JavaScript event handlers, namely onkeypress, onKeyDown, and onKeyUp, can offer smooth supervision over user inputs, enabling instant feedback and validation.
See this onkeypress handler in action:
This bad boy here is making sure the user doesn't exceed the limit by keeping an eye on each keystroke.
Tackling sneaky edge cases
Relying solely on maxlength? Be warned, some users may attempt to paste content longer than your limit and bypass it. You cannot blink on such cases and they need to be tackled with JavaScript validations:
And let's not forget about server-side validation, a steady guard post on the front line as those client-side restrictions can easily be circumvented.
Live feedback for user-friendly UI
Guiding users with information on the character limits is good UX design. With CSS, you can offer a visual hint when the limit is nearly reached and provide an error message if crossed. Real-time updates on character count can be implemented using JavaScript:
User-inclined prompts and Description
Clear cut directions for users go a long way in improving accessibility and enhancing the user experience. Include prompts or instructions adjacent to the input field:
Reusable JavaScript for code efficiency
Instead of injecting JavaScript here and there in your code, create a reusable function. Pass a target element and a character limit as parameters to the function. It's best for your code's readability and maintenance:
Mobile-user thoughtfulness
Coding with mobile users in mind means keeping things simple and responsive. They interact differently from desktop users so a responsive interface is always welcome.
Was this article helpful?