65.9K
CodeProject is changing. Read more.
Home

Multiline Textbox Length Validator Control

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.88/5 (9 votes)

Apr 15, 2004

1 min read

viewsIcon

139766

downloadIcon

2352

A validator control that limits the number of characters allowed in a textbox when the mode is set to multiline.

Introduction

It has annoyed me for a while now that the MaxLength attribute does not work for textboxes with the TextMode property set to MultiLine. Although a CustomValidator works for this sort of validation, I wanted something that was easier and quicker to implement. I also wanted some experience of writing controls, so I decided to write my own validator.

Using the Control

The control first needs to be registered on the aspx page:

<%@ Register TagPrefix="controls" Namespace="Web.Controls" Assembly="Web.Controls" %>

It can then be added to the form:

<controls:TextLengthValidator id="ValidLength" runat="server" 
    ControlToValidate="TextBox1" MaxLength="10" DisplayCharactersEntered="true" 
    Text="String too long<br>" />

Since the control inherits from BaseValidator, it has many of the same properties as the other .NET validator controls, however there are 2 additions:

  • MaxLength
  • DisplayCharactersEntered

As you can probably guess, MaxLength is the maximum number of characters allowed in the textbox. DisplayCharactersEntered was added because of a request from my boss who wanted the number of characters the user had entered displayed along with the error message. If this property is true, the string (xx characters entered) is appended onto the end of the validator text.

The control also does client side checking on UpLevel browsers. To get this to work though, the file CheckLength.js should be placed in a folder TextLengthValidator at the root of the website. This file is included with the control source.

Conclusion

That's pretty much it for just now. I haven't added any design support, I've still to read up on that. Once I have, you may see an improved version of my little validator. In the meantime, if anyone has any comments, get in touch.