Explain Codes LogoExplain Codes Logo

Limit number of characters allowed in form input text field

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Jan 24, 2025
TLDR

To restrict the number of characters in an input field, use the maxlength attribute in the input tag:

<input type="text" maxlength="10">

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:

<input type="text" id="limitedInput" onkeypress="limitCharacters(event)"> <script> function limitCharacters(event) { if (document.getElementById('limitedInput').value.length >= 10) { event.preventDefault(); // Sorry user, can't press that key. } } </script>

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:

document.getElementById('limitedInput').addEventListener('input', function() { const maxLength = 10; if (this.value.length > maxLength) { this.value = this.value.substring(0, maxLength); // If too long? Chop, chop! } });

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:

document.getElementById('limitedInput').addEventListener('input', updateCount); function updateCount() { const count = this.value.length; document.getElementById('charCount').textContent = `Characters: ${count}/10`; // Live updates, fresh from the kitchen! }
<span id="charCount">Characters: 0/10</span>

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:

<label for="username">Username (max 10 characters):</label> <input type="text" id="username" maxlength="10" aria-describedby="usernameHelp"> <small id="usernameHelp">Enter up to 10 characters. Yeah, short and sweet!</small>

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:

function enforceMaxLength(field, maxChars) { field.value = field.value.substring(0, maxChars); // Too long? Chop it off! } // Usage const inputField = document.getElementById('myInput'); inputField.addEventListener('input', () => enforceMaxLength(inputField, 10));

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.