Click here to Skip to main content
15,881,812 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET - Limit Number of Characters in TextBox Control

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
20 May 2010CPOL1 min read 40.2K   1   4   5
Limit/count number of characters in ASP.NET TextBox control
I was revisiting JavaScript used to limit the number of characters in a TextBox control, but the problem with this script was that it did not work correctly with multiple TextBox controls on the web page and was not cross-browser compatible. In this post, I rewrite it to ease the mentioned problems.

Introduction

Recently, I was revisiting the JavaScript used to limit the number of characters in a TextBox control. This client-side script utilized document.getElementById method and the control ID for HTML markup that was generated by ASP.NET. The problem with this script was that it did not work correctly with multiple TextBox controls on the web page and was not cross-browser compatible. So I decided to rewrite it to ease the mentioned problems. Shown in Listing 1 is the new content of the JavaScript. There are two functions that reside in it, namely validateLimit and get_object.

The former function accepts three parameters:

  1. TextBox object
  2. HTML Div id (to hold the text)
  3. Maximum number of characters the TextBox control can hold

The purpose of the later function is to ensure that modern and older browsers are able to access the form elements.

Listing 1

JavaScript
function validateLimit(obj, divID, maxchar) {

    objDiv = get_object(divID);

    if (this.id) obj = this;

    var remaningChar = maxchar - trimEnter(obj.value).length;

    if (objDiv.id) {
        objDiv.innerHTML = remaningChar + " characters left";
    }
    if (remaningChar <= 0) {
        obj.value = obj.value.substring(maxchar, 0);
        if (objDiv.id) {
            objDiv.innerHTML = "0 characters left";
        }
        return false;
    }
    else
    { return true; }
}

function get_object(id) {
    var object = null;
    if (document.layers) {
        object = document.layers[id];
    } else if (document.all) {
        object = document.all[id];
    } else if (document.getElementById) {
        object = document.getElementById(id);
    }
    return object;
}
//http://lawrence.ecorp.net/inet/samples/regexp-format.php#convert
function trimEnter(dataStr) {
    return dataStr.replace(/(\r\n|\r|\n)/g, "");
}

Putting everything together.

Listing 2

HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Without master page</title>
     <script type="text/javascript" src="js/JScript.js" ></script>
</head>
<body>
    <form id="form1" runat="server">
     <div> <br />
    <div id="lblMsg1">240 characters left</div>
    <asp:TextBox ID="TextBox1" runat="server" Height="50px" 
    MaxLength="240" TextMode="MultiLine"
                    Width="600px" ToolTip="Summary:(240 characters)" 
                    onkeyup="return validateLimit(this, 'lblMsg1', 240)"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="TextBox1" Display="Dynamic" 
            SetFocusOnError="True">*</asp:RequiredFieldValidator>
    <br /><br /><br />
    <div id="lblMsg2">300 characters left</div>
    <asp:TextBox ID="TextBox2" runat="server" Height="50px" 
    MaxLength="300" TextMode="MultiLine"
                    Width="600px" ToolTip="Summary:(300 characters)" 
                    onkeyup="return validateLimit(this, 'lblMsg2', 300)"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ControlToValidate="TextBox2" Display="Dynamic" 
            SetFocusOnError="True">*</asp:RequiredFieldValidator>
    <br /> <br />
    <asp:Button ID="Button1" runat="server" 
    onclick="Button1_Click" Text="Button" />
    <br />
    </div>
    </form>
</body>
</html>

Here is the output:

Figure 1

characters count

Conclusion

If you find any bugs or disagree with the contents, please drop me a line and I'll work with you to correct it.

I would suggest downloading the demo and explore it in order to grasp the full concept of it because I might have left out some useful information.

IE, Firefox, Google Chrome, Safari

Tested on IE 6.0/7.0/8.0, Google Chrome, Firefox, Safari

Resources

History

  • 20th May, 2010: First release
  • 20th May, 2010: Added new function trimEnter to replace enter key with empty string.

License

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


Written By
Software Developer (Senior)
United States United States
I have over 10 years of experience working with Microsoft technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an aptitude for learning new skills quickly.

Comments and Discussions

 
Generaltry keydown event, If I remember properly... it fires with p... Pin
Xmen Real 10-Jun-10 7:03
professional Xmen Real 10-Jun-10 7:03 
Generalhi Enver, I agreed with you, there is problem with copy-pas... Pin
Bryian Tan23-May-10 11:26
professionalBryian Tan23-May-10 11:26 
GeneralThis checks only keys, but user can copy-paste using mouse o... Pin
Enver Maroshi21-May-10 3:38
Enver Maroshi21-May-10 3:38 
Generalhi, can you give it a try again? I added a function to repla... Pin
Bryian Tan20-May-10 17:42
professionalBryian Tan20-May-10 17:42 
GeneralSmall Issue of above code with following scenario. When we p... Pin
Member 397960619-May-10 20:53
Member 397960619-May-10 20:53 

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

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