When collecting input from the use it's often necessary to limit the
amount of text entered into a text field. For normal text inputs we
have the maxlength attribute, but that is a bit crude and
doesn't apply to textareas.
Counting characters as you type
Here is a simple demonstration of a text input when you can enter any
amount of text. The character and word counts are displayed, but no
limits are enforced:
What we're looking for is a solution that will let us limit the text
input either by the number of characters or by the number of words, and to
have some kind of feedback presented to the user as they approach the
limit.
All of the examples on this page use the exact same JavaScript code
just with different settings. The source code can be found below.
If any of the input values are out of bounds an HTML5 error message
will appear. Here is a screenshot of how that might look:
Sample HTML Markup
Here is some example HTML code for setting up a textarea input with a
word counter and a limit on the number of words:
We haven't addressed this directly as there are too many variables
involving the cursor position, any current selection, and the text to be
pasted.
The best solution is probably just to accept the pasted text and then
truncate the contents of the textarea using
either JavaScript or a back-end script.
This is great! However, I can copy and paste past the limits...
One could programmatically truncate the text that is transmitted, or ignore anything over the limit...
The problems is that 'paste' doesn't trigger our event handlers, but if you put this into a FORM you will see that an HTML5 validation message will appear if there is too much text when you try to submit. I'll be adding that to the page.
Richard Kolseth 2 February, 2023
This is great! However, I can copy and paste past the limits...
One could programmatically truncate the text that is transmitted, or ignore anything over the limit...
The problems is that 'paste' doesn't trigger our event handlers, but if you put this into a FORM you will see that an HTML5 validation message will appear if there is too much text when you try to submit. I'll be adding that to the page.