Maximum Characters for Text Entry Boxes
Some people can get rather verbose when typing into form field text boxes.
They are likely to get tired of typing after a while so it isn't usually a problem, unless you store form submissions in a database and there is a maximum number of characters allotted for that particular field.
What might be a problem is people pasting in a huge amount of text, especially if you store form submissions and prefer not to use up your disk space that way.
Form submissions have a maximum size. A generous size, usually. But still a maximum.
But the biggest bother may be that, with a submission of lots and lots of text, you may feel compelled to read the entire tome. Also consider the effect of storing all that in a database.
In this article, you will learn how to impose a maximum number of characters that form type="text"
and textarea
fields are allowed to accept.
Enforcing a maximum character length for text and textarea form fields is fairly easy to do.
Here are examples. The text field allows a maximum of 25 characters and the textarea field a maximum of 100 characters.
As the person types, or pastes something in, JavaScript checks the length. If the length is too long, the JavaScript truncates the form field value to the allowed length.
Each form field with its value length checked, has an onkeyup
attribute that calls the JavaScript function.
Here is the JavaScript function. There is no customization. The function can be anywhere on the web page where JavaScript can run. Near the end of the page, immediately above the </body>
tag can be a good spot.
<script type="text/javascript"> function MaxFormFieldLength(field,len) { if(field.value.length > len) { field.value = field.value.substr(0,len); } } </script>
With that JavaScript on your page, your form fields may have content-length protection.
To use the JavaScript, insert this attribute into the type="text"
or textarea
field that will have a content limit. Here is an example.
onkeyup="MaxFormFieldLength(this,200)"
To implement, do these two steps.
-
Insert the above attribute into a
type="text"
ortextarea
field. -
Replace
200
with the maximum number of characters.
Here is an example.
<textarea onkeyup="MaxFormFieldLength(this,350)" name="test" style="height:1in; width:100%;"></textarea>
In the above source code, the textarea
field accepts a maximum of 350
characters.
After the JavaScript is on the page, all you have to do is insert the onkeyup
attribute into any form fields where you want to limit the number of characters of text it will accept.
(This article first appeared with an issue of the Possibilities newsletter.)
Will Bontrager