Setting a character limit on a multi line text box in 2.0

I looked all around to find this code when looking for it the other day. There were plenty of places that explained how to do this, but I couldn’t easily find something that JUST worked in the case I needed it to.

We had a site we were developing at work, written in ASP.Net 2.0 (C#). The user the software was targeted to is famous for ‘not following directions’, and we needed to restrict the number of characters they could type into the field. You see this in many places online, and quite honestly, it can even help the user experience. In Visual Studio 2005, you can do this easily on a text box by setting the ‘Max Length’ property. But if its a multiline text box, that wont work. It has to do with how multiline text boxes are rendered versus other text boxes. As I said before, many sites explained how to do this, but nothing actually JUST worked in our situation, so I have placed here code that DOES work, and in most browsers.

To start, one would place the following code in the ASPX page.

function textboxMultilineMaxNumber(txt,maxLen){
if(txt.value.length > (maxLen-1))return false;
// --></script>

The code above is basically a javascript that checks the length of the text in the textbox, and compares it against your maximum length. As long as this is true, you would be able to insert text into the box, then once it hits false, you can no longer enter text.

In your code behind, you need to then need to add an attribute to the text box, to link this JS to the text box.

txtNotes.Attributes.Add("onkeydown", "return textboxMultilineMaxNumber(this,250)");

This of course assumes that your textbox is called txtNotes. This particular line limits the text to 250 characters.

We have found this to work in most browsers. There are ‘gotchas’ of course, including users having javascript turned off and that if you copy and paste code into the box, it will still allow that. Therefore, follow general good practices and still check that your user is only entering the amount of text they can!


2 thoughts on “Setting a character limit on a multi line text box in 2.0

  1. So I tried this script out. It works pretty well. However there is a bug. Once you get to 250 characters you can’t backspace.

  2. dear sir,

    i have used this code in my project, it works fine, but if i want toedit or delete that data it doen’nt allow???pls send me the solution

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s