Click here to Skip to main content
Click here to Skip to main content

Multiline TextBox with MaxLength Validation

, 12 Mar 2006
Rate this:
Please Sign up or sign in to vote.
A simple extension of the existing TextBox control to attach JavaScript for maxlength validation.

Introduction

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
                Attributes.Add("onkeypress","doKeypress(this);");
                Attributes.Add("onbeforepaste","doBeforePaste(this);");
                Attributes.Add("onpaste","doPaste(this);");
                // Add attribute for access of maxlength property on client-side
                Attributes.Add("maxLength", this.MaxLength.ToString());
                // Register client side include - only once per page
                if(!Page.ClientScript.IsClientScriptIncludeRegistered("TextArea"))
                {
                    Page.ClientScript.RegisterClientScriptInclude("TextArea", 
                        ResolveClientUrl("~/js/textArea.js"));
                }
            }
            base.OnPreRender(e);
        }
    }
}

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;
     if(maxLength)
     {
          event.returnValue = false;
     }
}
// Cancel default behavior and create a new paste routine
function doPaste(control){
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
     if(maxLength){
          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.

<pages>
   <controls>
    <add tagPrefix="CustomControls" 
      namespace="CustomWebControls" 
      assembly="CustomWebControls"></add>
   </controls>
</pages>

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!

License

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
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 Pinmembertidkerohit12-Oct-11 3:18 
GeneralWell done thanks PinmemberMelih Gümüşçay18-Jul-09 3:32 
RantRe: Well done thanks Pinmemberhfrmobile3-Mar-10 23:06 
GeneralClient code work on ff & ie Pinmemberramip4-Apr-09 1:25 
Generalgud 1 : Multiline TextBox with MaxLength Validation PinmemberCoder Sumi1-Feb-09 23:51 
GeneralI'm sorry, but forget about TextArea behaving like a TextBox. Firefox / IE / Chrome [modified] Pinmemberviolentkun12-Dec-08 2:25 
1) The OnPaste approach cannot be cross-brower, although oninput (gecko) can emulate Onpaste (IE), by complaring previousValue and Value, and selectionStart/selectionEnd (gecko) can emulate getSelection or selection.createRange (IE), BUT NOT clipboardData(IE) due to security reasons. So theres actually no solution for Paste until some fix in the current html specification.
 
2) Returning False on Keypress/Keydown cannot be an approach as it will cause problem when u try to highlight some longer text and replacing with a char. U can workaround this by detecting if theres any Characters Highlighted by using selectionstart/selectionend for Chrome and FireFox and selection for IE. If the KeyCode is 13 (newline), make sure the characters highlighted is more than 1 char.
 
- It will also cause problem when u are using a Language Bar. U can workaround this using keypress for Normal characters, while keyUp for other foreign languages. In Firefox/IE/Chrome, Language Bar input event will not be detected by KeyPress but KeyUp or Keydown.
 
- It will also cause problem if u didnt check for keyCode for Tab, Backspace, arrows. (8,9,46,47,48,49 if i didnt recall wrongly)
 
3) Database support. Remember to use Nvarchar instead of varchar as some characters will take up 1 length in Input and store as 2 length in Database. Using RegEx in .NET Validation, one may consider the difference in the Length for newline. '/n' for Gecko based browser for newline while '/r/n' for IE, but may not be necessary as the Database will save what it see in Input. still it is a good practise.
 
Considering all the problems especially the PASTING constraint. There's no way to make a TextArea behaving like a Textbox. The only fleasible solution is to:
- allow user to key whatever they want, while u display the "Characters Remaining: 100". For .net can use the customvalidator with regex and for javascript u can also try to catch event during KeyUp,OnFocus,OnChange,Oninput,Onpaste.
- Optional to always truncate substring ur textarea on KeyUp (wont work with KeyDown/KeyPress) so the users will understand no matter how hard they try to type or copypaste, their extra characters will vanish.
- Optional to prompt users during onsubmit/save.
- truncate the extra characters before u save to database or files.
- While we all think there's a solution, i will like to point out that even big player like Youtube also need to do ths but Youtube never catch event during Paste and ctrl-V. They can really catch it with oninput or onpaste for perfection.
 
modified on Friday, December 12, 2008 8:40 AM

QuestionWhy not use a Regular Expression Validator? PinmemberJoe Gakenheimer )23-Jun-08 2:26 
GeneralProblems w/ AJAX update panels PinmemberJoAnn Morse31-May-08 8:13 
GeneralRe: Problems w/ AJAX update panels PinmemberAstynax77727-Dec-08 7:50 
GeneralThanks Pinmembercarladinmc14-Apr-08 2:32 
GeneralFixed for Firefox PinmemberMember 436197826-Feb-08 2:16 
GeneralRe: Fixed for Firefox Pinmemberjmoore653-Mar-08 3:57 
GeneralRe: Fixed for Firefox Pinmemberhfrmobile3-Mar-10 23:05 
GeneralNew line PinmemberAstynax77720-Feb-08 7:52 
GeneralRe: New line Pinmembersar11234-Sep-09 10:27 
GeneralRe: New line PinmemberAstynax7774-Sep-09 10:47 
GeneralFirefox Pinmemberhalexic30-Mar-07 1:32 
GeneralRe: Firefox Pinmemberhfrmobile3-Mar-10 23:19 
QuestionUpdatePanel Pinmemberjlweand13-Mar-07 22:24 
GeneralGreat work, paste issue PinmemberJuan Martin23-Jan-07 9:27 
GeneralThank you very much Pinmembermsg2rk17-Jan-07 20:43 
GeneralError Pinmembermishenkovks8-Nov-06 23:25 
Generalthanx for the article... another nice solution... PinmemberSina Falahati31-Oct-06 7:59 
GeneralRe: thanx for the article... another nice solution... PinmemberYen Dutt31-Oct-06 17:48 
GeneralRe: thanx for the article... another nice solution... PinmemberSina Falahati1-Nov-06 3:13 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 12 Mar 2006
Article Copyright 2006 by Yen Dutt
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid