Click here to Skip to main content
Click here to Skip to main content
Go to top

TEXTAREA Max length check

, 6 Aug 2007
Rate this:
Please Sign up or sign in to vote.
Limit number of chars allowed in text area

Introduction

Article describes how to limit the number of allowed characters in textarea.

Background

TextBox has maxlength attribute to limit the number of allowed characters. But TextArea does not have any attributes to control that. We will use simple javascript to control it.

Using the code

We will write two function handlers to handle keypress and paste

//
// Any source code blocks look like this

  function maxLength(field,maxChars)
 {
       if(field.value.length >= maxChars) {
          event.returnValue=false;
          return false;
       }
 }  

 function maxLengthPaste(field,maxChars)
 {
       event.returnValue=false;
       if((field.value.length +  window.clipboardData.getData("Text").length) > maxChars) {
         return false;
       }
       event.returnValue=true;
 }

//

maxLength() will be used for keypress event and maxLengthPaste will be used for onPaste event.

Add this code to your html or generate this code

<textarea rows="5" cols="6" onKeyPress='return maxLength(this,"30");' onpaste='return maxLengthPaste(this,"30");'></textarea>

It won't allow you to enter more than 30 chars, same time it will not allow you to paste more than 30 chars.

You can change the code to alert the user to recheck their data. Just insert an alert message before return false statement.

//
// Any source code blocks look like this

  function maxLength(field,maxChars)
 {
       if(field.value.length >= maxChars) {
          event.returnValue=false; 
          alert("more than " +maxChars + " chars");
          return false;
       }

 }  

 function maxLengthPaste(field,maxChars)
 {
       event.returnValue=false;
       if((field.value.length +  window.clipboardData.getData("Text").length) > maxChars) {
         alert("more than " +maxChars + " chars");
         return false;
       }
       event.returnValue=true;
 }

//

If you do not want to pass the field as an argument to the function, you can take it from event object.

var field=  event != null ? event.srcElement:e.target;

You can refer to my other article "Change Background color of current focus element" to assign global event handler. In that case, you do not need to pass maxLength as an argument, make it as an attribute, so that you can register global handler for textarea and use maxLength attribute of the field to validate the length.

<script language="javascript">
function attachEvent(name,elementName,callBack) {
    var element = elementName;
    if(typeof elementName == 'string') 
      element = document.getElementById(elementName);
    }
    if (element.addEventListener) {
      element.addEventListener(name, callBack,false);
    } else if (element.attachEvent) {
      element.attachEvent('on' + name, callBack);
    }
}
function maxLength()
 {
 
       var field=  event != null ? event.srcElement:e.target;
       if(field.maxChars  != null) {  
         if(field.value.length >= parseInt(field.maxChars)) {
           event.returnValue=false; 
           alert("more than " +field.maxChars + " chars");
           return false;
         }
       }
 }  

 function maxLengthPaste()
 {
       event.returnValue=false;
       var field=  event != null ? event.srcElement:e.target;
       if(field.maxChars != null) {
         if((field.value.length +  window.clipboardData.getData("Text").length) > parseInt(field.maxChars)) {
           alert("more than " +field.maxChars + " chars");
           return false;
         }
       }
       event.returnValue=true;
 }
</script>

Generate or create this html

<textarea rows="5" cols="6" maxLength="30" id="textarea1"></textarea>

<script language="javascript">
  attachEvent("keypress","textarea1",maxLength);
  attachEvent("paste","textarea1",maxLengthPaste);
</script>


or you can assign gloabl handler
<script language="javascript">

function setTextAreaListner(eve,func) {
   var ele = document.forms[0].elements;
   for(var i = 0; i <ele.length;i++) {
    element = ele[i];
    if (element.type) {
      switch (element.type) {
        case 'textarea':
        attachEvent(eve,element,func);
       }
     }
  }
}
</script>
<script language="javascript">
 setTextAreaListner("keypress",maxLength);
 setTextAreaListner("paste",maxLengthPaste);
</script>

For netscape clipboard manipulation, refer to this forum

http://www.gamedev.net/community/forums/topic.asp?topic_id=281951

.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

senthil karuppaiah
Web Developer
United States United States
Fourteen years of progressive experience in Software Product Development, tactical planning, project and client management, demonstrated success in leadership, critical thinking, problem solving and analysis. Diverse knowledge and experience with multiple development methodologies, reengineering, software engineering, and integration of heterogeneous systems.

Comments and Discussions

 
QuestionWhy not trim the input? PinmemberAnth_Humphreys27-Nov-07 4:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 6 Aug 2007
Article Copyright 2007 by senthil karuppaiah
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid