Thursday, 26 November 2009

ASP.NET: Setting the maximum number of characters in a multiline text box

Bizarrely, ASP.NET includes an out of the box setting which allows you to set the maximum number of characters on an ordinary text box, but not on a multiline text box.

Now there may be a good reason for this, and if there is I would love to be enlightened.

There is no less need for a multiline textbox control to be properly validated than any other text box - perhaps it is even more important since the user might have spent ages typing something in, only to be rebuked for exceeding the maximum number of characters and to be punished by losing what they'd typed.

A friendly character on the ASP.NET forums offered this simple JavaScript solution:

<script language="javascript">

function Count(text,long)

   var maxlength = new Number(long); // Change number to your max length.

   if (text.value.length > maxlength){

      text.value = text.value.substring(0,maxlength);

      alert(" Only " + long + " chars");



Then just add these to the multiline textbox's markup: onKeyUp="Count(this,200)" onChange="Count(this,200)".