Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 367, trackbacks - 0

My Links

News

Archives

Image Galleries

Restrict number of characters to be entered in the MultiLine TextBox

This example demonstrates on how are we going to limit the number of characters to be typed into the TextBox using JavaScript and display the remaining characters in a Label Control.

<script type="text/javascript" language="javascript">
   
     function validatelimit(obj, maxchar)
     {
   
        if(this.id) obj = this;
       
        var remaningChar = maxchar - obj.value.length;
        document.getElementById('<%= Label1.ClientID %>').innerHTML = remaningChar;

            if( remaningChar <= 0)
            {
               obj.value = obj.value.substring(maxchar,0);
               alert('Character Limit exceeds!');
               return false;

            }
            else
            {return true;}
     }

    </script>

<body  runat="server">
    <form id="form1" runat="server">

        <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" onkeyup="validatelimit(this,300)">   </asp:TextBox>
        <asp:Label ID="Label1" runat="server" Text="0"></asp:Label>

   </form> 

</body>

Note: 300 is the MAX length of the characters in the TextBox..Just change the value of 300 based on your requirements..

Print | posted on Tuesday, February 17, 2009 3:44 PM |

Feedback

Gravatar

# re: Restrict number of characters to be entered in the MultiLine TextBox

Thank You very much....It is working fine..........
5/22/2009 4:38 AM | Krishnanunni
Gravatar

# re: Restrict number of characters to be entered in the MultiLine TextBox

It's Very Nice Article
6/27/2009 2:30 AM | Madhusudhan
Gravatar

# re: Restrict number of characters to be entered in the MultiLine TextBox

Unfortunately it doesn't seem to work if the users copy and paste into the textbox.
7/19/2009 9:30 PM | anon
Gravatar

# re: Restrict number of characters to be entered in the MultiLine TextBox

I agree with Anon...
This does not work if the user uses the mouse/keyboard to paste the text in the text box..
Tried a lot for it but could not make it work...
What is the event that will track the pasting in the text box?
can anybody help with it?????
7/30/2009 2:55 AM | Louie
Gravatar

# re: Restrict number of characters to be entered in the MultiLine TextBox

@Anon and Louie,

In this example, I didn't include on how to restrict the user to do a copy and paste.. You'll need to create a JavaScript to handle that as demonstrated in this example:

http://csharpdotnetfreak.blogspot.com/2009/01/disable-copy-paste-javascript-right.html

HTH
7/30/2009 2:54 PM | Vinz
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: