65.9K
CodeProject is changing. Read more.
Home

Validate Max Length of Multi-Line Textbox

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Sep 27, 2010

CPOL

1 min read

viewsIcon

25282

This post shows how to validate the max length of a multi-line textbox.

Introduction

ASP.NET has an uncanny knack for swallowing up huge chunks of my day on silly little things.

After setting the MaxLength properties on all my text boxes before putting my app into test, I was shocked to hear the testers were able to put as much data as they liked into some fields, and were getting database errors about data being truncated.

Sure enough... the MaxLength property doesn't work on Multi-Line Textboxes. A fact that apparently I'm one of the last to know, but heh! I'm a reluctant ASP.NET programmer and where I come from MaxLength works dammit.

So... to save someone else wasting a morning, here's my solution:

  1. Add the following JavaScript to your page:
    <script language="javascript" type="text/javascript">
    function CommentsMaxLength(text,maxLength)
    {
       text.value = text.value.substring(0,maxLength);
    }
    </script>
  2. Add the following to the definition of your textbox:
    onKeyUp="CommentsMaxLength(this,100)" onChange="CommentsMaxLength(this,100)"
    

    And that's it. Change the 100 to whatever Maxlength you'd like.

Bonus Points

This part is optional, but I like it, it gives a count down of the number of characters you have left.

  1. Add a label over the text box in question. e.g. a label called 'lblComments' if your text box stores comments.
    Note the name, we'll need it later.
  2. Change the JavaScript function above to the following:
    <script language="javascript" type="text/javascript">
    function CommentsMaxLength(text,maxLength)
    {
        var diff = maxLength - text.value.length;
        if (diff < 0){
            text.value = text.value.substring(0,maxLength);
            diff=0;
        }
        document.getElementById('<%= lblComments.ClientID %>').innerText = 
    						"Comments (" + diff + ")";
    }
    </script>

Note the Name of your label is needed for getElementById.

The rest is the same.
Simples.
-Rd