Journal » Post
|
|
I was fixing a bug on the guestbook section earlier and decided to add the maxlength attribute to the form. When I tried to validate the code using the XHTML 1.0 Transitional specs it had 1 error. It seems the textarea input field doesn't support the maxlength attribute. For the sake of security I decided to implement a JavaScript solution after seeing a similar implementation on QuirksBlog. I got the concept from that tutorial and expanded on the idea. The requirements of the script I made were simple: to be unobtrusive, must validate in XHTML 1.0 Transitional, and be modular. The example at QuirksBlog had several limitations such as: it will not validate since it still relied on using the maxlength attribute within the textarea tag itself, and it will not deny input if it has passed the set maxlength value. So to make the long story short I'll show you my code.
What this basically does is loop through all the textarea tags and searches for the ml-(number) class name. For example, you want to set the maxlength of a particular textarea to 500 characters, you would add ml-500 to that textarea class attribute, where ml- would be the marker for the script and 500 the actual maxlength limit. This way we just append values to the class attribute so that the code will still validate. This will not affect any style/class you already have for that textarea, you would just separate them with spaces like so:
To see this in action, just copy and paste the code and call the setMaxLength function on the window.onload event. I tested this on the following browsers:
|



