Restricting visitor input from a text box – HTML TEXTAREA element

Restricting visitor input from a text box – HTML TEXTAREA element cover image
  1. Home
  2. HTML
  3. Restricting visitor input from a text box – HTML TEXTAREA element

Your forms might have text boxes (created using the <TEXTAREA> tag) through which you plan to collect some details from your visitors. Now, it’s always better to restrict such input to a defined number of words. We don’t want users to send us thousands of words, do we?

We’ll employ the function we met in the last tip (Counting words entered in a text box) and modify it so that we receive only a defined number of words.
The function discards everything after the 30th word.

function count_words(tbox_input)
   {
   var msg = "";
   var c = 0;
   w = tbox_input.value.split(" ");
   no_words = w.length;
   for (x = 0; x < no_words; x++)
      {
      if (c >= 30)
         {
         alert("Only thiry words please!");
         tbox_input.value = msg;
         break;
         }
      msg = msg + w[x] + " ";
      c++;
      }
   return false;
   }

Two variables msg and c are initialized when the function is called. The entire value of the TEXTAREA element is split using split() method with the space character as a separator of words. The result is stored in an array w. The number of words is calculated with the length property. A for loop is then employed with which we add the first thirty elements of the array and store the result in variable msg. Variable c keeps a tab on the number of words being added to msg. At each iteration of the loop, the value of c is checked. If it is greater than 30 (our limit), we display an alert, assign TEXTAREA the value msg (the first thirty words) and break out of the loop.

The function above always returns false. You would have to change it to return false ONLY when the number of words is more than 30.

Here is how you do it:

function count_words(tbox_input)
   {
   var msg = "";
   var c = 0;
   var er = 0;
   w = tbox_input.value.split(" ");
   no_words = w.length;
   for (x = 0; x < no_words; x++)
      {
      if (c >= 30)
         {
         alert("Only thiry words please!");
         tbox_input.value = msg;
         er = 1;
         break;
         }
      msg = msg + w[x] + " ";
      c++;
      }
   if (er)
      {
      return false;
      }
   return true;
   }

Click here to see how this works!

Note: You should not rely on only client-side validation of TEXTAREA values. Client-side validation will not work on old browsers or browsers with JavaScript turned off. It’s always better to validate user input through server side scripts too!

HTML JavaScript