Click here to Skip to main content
14,735,324 members
Articles » Web Development » Custom Controls » General
Posted 12 Mar 2006


45 bookmarked

Multiline TextBox with MaxLength Validation

Rate me:
Please Sign up or sign in to vote.
4.61/5 (29 votes)
12 Mar 2006CPOL
A simple extension of the existing TextBox control to attach JavaScript for maxlength validation.


In almost all web projects, we require a multiline TextBox control. It was annoying to find that the maxLength property doesn't work on multiline textboxes. There are various solutions suggesting to use validator controls to validate length. I suggest that we should put a validator as well as extend our control so that the user will not be able to enter characters more than the length specified.

Extending the TextBox

To achieve this, I tried extending the ASP.NET TextBox WebControl.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;

namespace CustomWebControls
    /// <summary>
    /// Extended TextBox control that applies
    /// javascript validation to Multiline TextBox
    /// </summary>
    public class TextArea: TextBox
        /// <summary>
        /// Override PreRender to include custom javascript
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
            if (MaxLength > 0 && TextMode == TextBoxMode.MultiLine)
                // Add javascript handlers for paste and keypress
                // Add attribute for access of maxlength property on client-side
                Attributes.Add("maxLength", this.MaxLength.ToString());
                // Register client side include - only once per page

Now our custom control is ready to use. In the above code block, it should be self-explanatory that if I find the TextBox's TextMode property to be MultiLine, I add custom JavaScript and a property to pass the maxLength on the client side. I take advantage of ClientScript to attach a JavaScript, only one per page. I chose to include JavaScript as an external file because this allows us to modify the JavaScript easily. In addition, the page will not be bloated and the script will be cached.

I created this control in a Project Library so that I can use this control in any of our projects.

JavaScript File

// Keep user from entering more than maxLength characters
function doKeypress(control){
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
     if(maxLength && value.length > maxLength-1){
          event.returnValue = false;
          maxLength = parseInt(maxLength);
// Cancel default behavior
function doBeforePaste(control){
    maxLength = control.attributes["maxLength"].value;
          event.returnValue = false;
// Cancel default behavior and create a new paste routine
function doPaste(control){
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
          event.returnValue = false;
          maxLength = parseInt(maxLength);
          var oTR = control.document.selection.createRange();
          var iInsertLength = maxLength - value.length + oTR.text.length;
          var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
          oTR.text = sData;

Using the Custom Control

To test the custom control, I created a test website and added a reference to the project. I wanted to avoid the hassle of adding the Register tag on each page, so I went ahead and added the following statements in the system.web section of web.config.

    <add tagPrefix="CustomControls" 



Now I created a test web page and added the control on the page as:

<CustomControls:TextArea runat="server" ID="testTextArea" 

   MaxLength="10" TextMode="MultiLine"></CustomControls:TextArea>

Then I added the JavaScript file in the JS folder.

Tested the solution and voila! My first attempt to create an extended custom Web Control is successful. I will appreciate your comments.

Summary of things I learned

  • Extending a Web Control is a breeze.
  • The new ClientScript property of Page. And the related IsClientScriptIncludeRegistered and RegisterClientScriptInclude properties.
  • Added the tag prefix in Web.Config instead of specifying it on each page.

Client Browsers Supported

  • IE 6.0

Other Notes

  • To get this control to work on other browsers also, we might need some modifications in the JS file.
  • This solution was developed in Visual Studio 2005. To convert it to Visual Studio 2003, we just need to change the calls for IsClientScriptIncludeRegistered and RegisterClientScriptInclude.
  • It's necessary to add validation controls also for length check. This will allow you to validate the input even if client-side script fails.

Thanks CodeProject for all the help!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Yen Dutt
Web Developer Airtel Broadband
India India
Despite my lack of interest, started trying coding at the age of 15 in Visual FoxPro. Got introduced to ASP in 2003 and started working for a US based client for a Youth Sports Management Application. In 2005, got Introduced to ASP.NET/ VB.NET and since then, it has become my passion. Recently joined Rapidigm Inc. as a software developer and looking forward to expand my knowledge base by sharing information with fellow coders in the Web World.

My interests include listening to music, trekking, traveling apart from coding!

Comments and Discussions

QuestionThanks Pin
tidkerohit12-Oct-11 4:18
Membertidkerohit12-Oct-11 4:18 
GeneralWell done thanks Pin
Melih Gümüşçay18-Jul-09 4:32
MemberMelih Gümüşçay18-Jul-09 4:32 
RantRe: Well done thanks Pin
hfrmobile4-Mar-10 0:06
Memberhfrmobile4-Mar-10 0:06 
GeneralClient code work on ff & ie Pin
ramip4-Apr-09 2:25
Memberramip4-Apr-09 2:25 
Generalgud 1 : Multiline TextBox with MaxLength Validation Pin
Coder Sumi2-Feb-09 0:51
MemberCoder Sumi2-Feb-09 0:51 
GeneralI'm sorry, but forget about TextArea behaving like a TextBox. Firefox / IE / Chrome [modified] Pin
violentkun12-Dec-08 3:25
Memberviolentkun12-Dec-08 3:25 
QuestionWhy not use a Regular Expression Validator? PinPopular
jgakenhe23-Jun-08 3:26
professionaljgakenhe23-Jun-08 3:26 
GeneralProblems w/ AJAX update panels Pin
JoAnn Morse31-May-08 9:13
MemberJoAnn Morse31-May-08 9:13 
GeneralRe: Problems w/ AJAX update panels Pin
Astynax77727-Dec-08 8:50
MemberAstynax77727-Dec-08 8:50 
GeneralThanks Pin
carladinmc14-Apr-08 3:32
Membercarladinmc14-Apr-08 3:32 
GeneralFixed for Firefox Pin
Member 436197826-Feb-08 3:16
MemberMember 436197826-Feb-08 3:16 
GeneralRe: Fixed for Firefox Pin
jmoore653-Mar-08 4:57
Memberjmoore653-Mar-08 4:57 
GeneralRe: Fixed for Firefox Pin
hfrmobile4-Mar-10 0:05
Memberhfrmobile4-Mar-10 0:05 
GeneralNew line Pin
Astynax77720-Feb-08 8:52
MemberAstynax77720-Feb-08 8:52 
GeneralRe: New line Pin
sar11234-Sep-09 11:27
Membersar11234-Sep-09 11:27 
GeneralRe: New line Pin
Astynax7774-Sep-09 11:47
MemberAstynax7774-Sep-09 11:47 
GeneralFirefox Pin
halexic30-Mar-07 2:32
Memberhalexic30-Mar-07 2:32 
GeneralRe: Firefox Pin
hfrmobile4-Mar-10 0:19
Memberhfrmobile4-Mar-10 0:19 
QuestionUpdatePanel Pin
jlweand13-Mar-07 23:24
Memberjlweand13-Mar-07 23:24 
GeneralGreat work, paste issue Pin
Juan Martin Diaz23-Jan-07 10:27
MemberJuan Martin Diaz23-Jan-07 10:27 
GeneralThank you very much Pin
msg2rk17-Jan-07 21:43
Membermsg2rk17-Jan-07 21:43 
GeneralError Pin
mishenkovks9-Nov-06 0:25
Membermishenkovks9-Nov-06 0:25 
Generalthanx for the article... another nice solution... Pin
Sina Falahati31-Oct-06 8:59
MemberSina Falahati31-Oct-06 8:59 
GeneralRe: thanx for the article... another nice solution... Pin
Yen Dutt31-Oct-06 18:48
MemberYen Dutt31-Oct-06 18:48 
GeneralRe: thanx for the article... another nice solution... Pin
Sina Falahati1-Nov-06 4:13
MemberSina Falahati1-Nov-06 4:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.