How to count character of TextBox in ASP.NET

Here, we will see how to check number of character has been inserted in the TextBox. A TextBox Which has max length 120 character and we insert a character in TextBox max length will be display 119 characters. When We enter 120 characters in the TextBox that will be the Max length. 

Drag and drop a TextBox on the page. Select TextBox and press F4 to property window.


Now add the following code in the Head section of the .aspx page.

<head runat="server">


    <style type="text/css">



            background-color: #FFFFFF;

            color: #000000;




            background-color: #FFCCCC;

            color: #ff0000;




    <script language="javascript">

        function textCounter1(field, maxlimit) {

            if (field.value.length > maxlimit) {

                field.value = field.value.substring(0, maxlimit);

                document.getElementById('message').className = "invalid";


                //alert('You have reached your maximum character limit.');


            else {

                document.getElementById('message').className = "valid";




            function textCounter(field, countfield, maxlimit) {

                if (field.value.length > maxlimit) // if too long...trim it!

                    field.value = field.value.substring(0, maxlimit);


                    countfield.value = maxlimit - field.value.length;





Now add the following code in the body section.


<body bgcolor="#FFFFFF">

<form name="blah" action="" method="post" runat="server">

    &nbsp;<asp:TextBox ID="message" runat="server" name="message" onkeydown="textCounter(this.form.message,this.form.remLen,120)"

        onkeyup="textCounter1(this.form.message, 120)" class="validentry"

        Height="101px" TextMode="MultiLine" Width="228px"></asp:TextBox>

    <br />

    <input readonly type="text" name="remLen" size="3" maxlength="3" value="120"

    position: absolute; style="width: 34px">Character left<br />

    <br />

    <br />



Now run the application and check number of character has been inserted in the TextBox.



Now Insert max length characters in TextBox.



Ebook Download
View all
View all