Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Maximum characters per word in a textarea

validation using Javascript


crazed canuck

8:03 pm on May 16, 2003 (gmt 0)

10+ Year Member

I am working on a simple custom content management system where a user can enter values into a form and have their new content update their website. The page that they can add content to is a pop-up window which has a width and height set to 400px.

The issue I am having is how to validate the maximum number of characters per word when a user types something into a textarea. ie. if someone types in:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa or a long url, the browser doesn't know where to break and thus creates a horizontal scrollbar and pushes around images.

Can someone point me to an example of where this has been done before? or have some pointers?



6:34 pm on May 17, 2003 (gmt 0)

WebmasterWorld Senior Member tedster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

That's a tough situation to handle well automatically - you may have seen some occasional side scrolling here on the forums, which we moderators always edit by hand.

The following idea is untested, off the top of my head.

If you want your javascript just to issue an alert to the user and refuse the input from the textbox [rather than inserting an appropriate line break] you might use string.split(" ") on the entire string of textarea input.

The split() method, with a space between the quotation marks, should generate an array where each of the individual words is a separate array element.

Then reverse sort the array by the length of its elements, so the longest word is in position 1. If the length of that first element is greater than your maximum, then send an alert to the user and refuse their input.

At least that seems to be one direction you could test out. Not sure how efficient it would be on a very long bit of text.

crazed canuck

5:55 pm on May 23, 2003 (gmt 0)

10+ Year Member

thanks, that worked! here is the code...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<script language="JavaScript">
function doOnChange()
var text = document.form0.test.value;
splitString = text.split(" ");
for (i=0; i <=splitString.length -1; i++)
if (splitString[i].length >= 10)
alert("The word " + splitString[i] + " is longer than 30 characters!");
<form action="test.html" name="form0" id="form0">
<textarea rows="10" cols="50" name="test" id="test" onChange="doOnChange()">This is a test area!</textarea>



6:12 pm on May 23, 2003 (gmt 0)

WebmasterWorld Senior Member tedster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

Glad it worked - and thanks for sharing the exact code that worked for you.

Featured Threads

Hot Threads This Week

Hot Threads This Month