[thelist] TIP: Limiting TextArea length

James Aylard evolt at pixelwright.com
Wed Mar 17 13:41:34 CST 2004

John.Brooking at sappi.com wrote:

>    One fly in the ointment is the possibility of pasting into a
> TEXTAREA, which does not cause the KeyPress event to fire,
> circumventing this check. Internet Explorer 5+ contains an onPaste
> event whose handler can contain the check. However, note that you
> must also take into account how many characters are waiting in the
> clipboard to know if the total is going to take you over the limit or
> not. Fortunately, IE also contains a clipboard object from the window
> object.[1] Thus:
>     <textarea onKeyPress="return ( this.value.length < 50 );"
> onPaste="return (( this.value.length +
> window.clipboardData.getData('Text').length) < 50 );"></textarea>

    For clarification, you don't need to check the clipboard. The onpaste
event fires when the paste occurs, allowing you to check the length of the
textarea value and truncate it if it exceeds the allowed limit.
    When I worked with this a couple of years ago, I found problems with
checking the textarea value immediately, and so I put in a 10ms setTimeout
before validating the length of the entry -- effectively creating an
onafterpaste event. The delay is so incredibly minute that it is transparent
to the user. In fact, the user won't even realize that the entire copied
value was ever actually pasted into the textarea; instead, it simply appears
that only the allowed number of characters were pasted into the textarea,
exactly as it would in a text-type input with a maxlength value.
    Another trick for IE-only environments is to take advantage of so-called
expando properties (or user-defined properties) for html elements. You can
create a "maxlength" property for the textarea, and reference that property
in your scripts (using the getAttribute() method). That is especially
flexible in environments where you have more than one textarea with more
than one length-limit value.

James Aylard

More information about the thelist mailing list