Limit the Length of Value in Textarea from ASP.NET

Even though HTML5 finally defines the "maxlength" attribute for TEXTAREA control (see the references at the end), the need to limit the length of a value and show the count to the end user is still there. In this small article I'm going to show you how to write a small JavaScript object that limits TEXTAREA value and how to implement this client object from an ASP.NET web page.

Here at Code Effects we use this functionality on pretty much all our sites. Even the comments form below this text uses it. But don't rush firing your copy of Fiddler just yet. The client-side nature of this function doesn't mean that we don't check all our inputs on the server :) In fact, we don't validate incoming data on the client at all (not even on our client-side web applications such as Web Scheduler!) The Limiter function that I'm going to build here is the only function that we use to "limit" user's input on the client. And we do this only because it's convenient for the user.

By the way, my name is Sergey. This is my first post in our new blog. Hope someone will find it useful.

Let's build a web page that contains an a TEXTAREA, a LABEL that shows the remaining number of characters, and a BUTTON that does nothing but posting the page on itself (the VS 2010 solution that contains this code is attached to this article in the References section).

<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="CodeEffects.Limiter.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Limiter</title>
<script type="text/javascript" src="/Limiter.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtTest" runat="server"
TextMode="MultiLine" Rows="10" Width="400"></asp:TextBox><br />
<span>Remaining character count:</span>
<asp:Label ID="lblCount" runat="server"></asp:Label><br /><br />
<asp:Button ID="btnTest" runat="server" Text="Post" Width="100" />
</div>
</form>
</body>
</html>


As you can see, this is a very basic web page. I'll get back to it later. For now, look at the SCRIPT tag in the HEAD. It references the Limiter.js file that we are going to create next.

function Limiter(txt, lbl, max)
{
function chars()
{
if (txt.value.length > max) txt.value = txt.value.substr(0, max);
lbl.innerHTML = max - parseInt(txt.value.length, 10);
};

chars();

txt.onkeyup = function (e) { chars(); };
txt.onblur = function (e) { chars(); };
};


Here we define an object Limiter that takes our TEXTAREA and LABEL controls as its first two parameters. It also takes a max number of characters it will allow users to type into the TEXTAREA.

First, it declares a private function "chars". This function will be used from multiple places withing the Limiter but it's useless outside of the object. Therefore, I declared it inside of the Limiter (JavaScript is The Good and The Evil at the same time, don't you agree?) The "chars" checks the current length of the TEXTAREA. It cuts the value if it's longer than the limit. It also calculates and displays the number of the remaining chars in the TEXTAREA. Pretty basic stuff, nothing special here.

The Limiter then calls the "chars" function to set everything up when it gets initialized on page load or post back. And then it subscribes to two events of the TEXTAREA - "keyup" and "blur". Both handlers of these events will call the "chars" function.

That's it on the client. Again, very basic. But it adds some nice functionality to the UI. Now let's get back to our web page and look at its C#:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CodeEffects.Limiter
{
public partial class Default : Page
{
private int max = 1000;

protected void Page_Load(object sender, EventArgs e)
{
this.AddLimiter(this.max);
}

public void AddLimiter(int limit)
{
if (this.txtTest.TextMode != TextBoxMode.MultiLine) return;

string NAME = "scrLimiter" + this.txtTest.ClientID;
Type type = this.GetType();

if (!this.ClientScript.IsStartupScriptRegistered(type, NAME))
this.ClientScript.RegisterStartupScript(
type,
NAME,
"new Limiter(document.getElementById('" +
this.txtTest.ClientID +
"'),document.getElementById('" +
this.lblCount.ClientID + "')," + limit + ");",
true);
}
}
}


The code declares a private global integer "max" that holds the max value for the Limiter. Normally, of course, you would want to keep this kind of data in config files. The code also declares the AddLimiter method. This method checks if the Limiter initialization hasn't been already added to the page. If not, it uses Page's ClientScript property to add the line of JavaScript to the end of the page's markup. This makes sure that our line gets executed after the DOM was initialized. Again, because the Limiter calls its private "chars" function on initialization, the LABEL will display the proper number on page load or post back. You don't need to do anything else other than calling the AddLimiter method on Page's Page_Load handler (weather it's a post back or not).

That's it. Download the project below, run it and see how easy it is.
ASP.NET JavaScript Next »
Comments:
Name (optional):
Comment (URLs are allowed and must start with http:// or https://; all tags will be encoded):
Remaining character count:
SPAMMER? Comments on this site are not included in page source. The stuff that you might post here WILL NOT be indexed by search engines.