Click here to Skip to main content
6,594,088 members and growing! (15,266 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Beginner

Multiline TextBox with MaxLength Validation

By Yen Dutt

A simple extension of existing TextBox control to attach javascript for maxlength validation.
Windows, .NET, ASP.NET, Visual Studio, WebForms, Dev
Posted:12 Mar 2006
Views:107,542
Bookmarked:36 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
21 votes for this article.
Popularity: 5.59 Rating: 4.23 out of 5
2 votes, 9.5%
1
1 vote, 4.8%
2
2 votes, 9.5%
3
2 votes, 9.5%
4
14 votes, 66.7%
5

Introduction

In almost all the web projects, we require a multiline TextBox control. It was annoying to find that 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 user will not be able to enter characters more than the length specified.

Extending TextBox

To achieve this, I tried extending 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 javascripts and a property to pass maxLength on 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 Javascript easily. In addition, page will not be bloated and 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 Custom Control

To test the custom control, I created a test website and added 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 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 page as:

<CustomControls:TextArea runat="server" ID="testTextArea" MaxLength="10" TextMode="MultiLine"></CustomControls:TextArea>

Then I added the javascript file in JS folder.

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

Summary of things I learned

  • Extending a web control is a breeze.
  • New ClientScript property of page. Related  IsClientScriptIncludeRegistered and RegisterClientScriptInclude property.
  • Added the tagPrefix 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 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Yen Dutt


Member
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!
Occupation: Web Developer
Location: India India

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 30 (Total in Forum: 30) (Refresh)FirstPrevNext
GeneralWell done thanks PinmemberMelih Gümüşçay4:32 18 Jul '09  
GeneralClient code work on ff & ie Pinmemberramip2:25 4 Apr '09  
Generalgud 1 : Multiline TextBox with MaxLength Validation PinmemberCoder Sumi0:51 2 Feb '09  
GeneralI'm sorry, but forget about TextArea behaving like a TextBox. Firefox / IE / Chrome [modified] Pinmemberviolentkun3:25 12 Dec '08  
GeneralWhy not use a Regular Expression Validator? PinmemberJoe Gakenheimer )3:26 23 Jun '08  
GeneralProblems w/ AJAX update panels PinmemberJoAnn Morse9:13 31 May '08  
GeneralRe: Problems w/ AJAX update panels PinmemberAstynax7778:50 27 Dec '08  
GeneralThanks Pinmembercarladinmc3:32 14 Apr '08  
GeneralFixed for Firefox PinmemberMember 43619783:16 26 Feb '08  
GeneralRe: Fixed for Firefox Pinmemberjmoore654:57 3 Mar '08  
GeneralNew line PinmemberAstynax7778:52 20 Feb '08  
GeneralRe: New line Pinmembersar112311:27 4 Sep '09  
GeneralRe: New line PinmemberAstynax77711:47 4 Sep '09  
GeneralFirefox Pinmemberhalexic2:32 30 Mar '07  
QuestionUpdatePanel Pinmemberjlweand23:24 13 Mar '07  
GeneralGreat work, paste issue PinmemberJuan Martin10:27 23 Jan '07  
GeneralThank you very much Pinmembermsg2rk21:43 17 Jan '07  
GeneralError Pinmembermishenkovks0:25 9 Nov '06  
Generalthanx for the article... another nice solution... PinmemberSina Falahati8:59 31 Oct '06  
GeneralRe: thanx for the article... another nice solution... PinmemberYen Dutt18:48 31 Oct '06  
GeneralRe: thanx for the article... another nice solution... PinmemberSina Falahati4:13 1 Nov '06  
GeneralExtending Textbox to open the default email-client on the client side PinmemberChakreee21:57 4 Sep '06  
GeneralStandard JavaScript PinmemberDeobrat Singh0:59 29 Aug '06  
GeneralRe: Standard JavaScript PinmemberAvornicesei Simona3:05 5 Sep '06  
GeneralRe: Standard JavaScript PinmemberChris Gruber3:12 9 Aug '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 Mar 2006
Editor:
Copyright 2006 by Yen Dutt
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project