Introduction
In almost all web projects, we require a multilineTextBox
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.NETTextBox
WebControl.//c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomServerControls
{
///
{
public override TextBoxMode TextMode
{
get { return TextBoxMode.MultiLine; }
}
protected override void OnPreRender(EventArgs e)
{
if (MaxLength > 0)
{
if (!Page.ClientScript.IsClientScriptIncludeRegistered("TextArea"))
{
Page.ClientScript.RegisterClientScriptInclude("TextArea", ResolveClientUrl("~/textarea.js"));
}
this.Attributes.Add("onkeypress", "LimitInput(this)");
this.Attributes.Add("onbeforepaste", "doBeforePaste(this)");
this.Attributes.Add("onpaste", "doPaste(this)");
this.Attributes.Add("onmousemove", "LimitInput(this)");
this.Attributes.Add("maxLength", this.MaxLength.ToString());
}
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
Java Script File
doBeforePaste(control)
{
maxLength = control.attributes["maxLength"].value;
if (maxLength)
{
event.returnValue = false;
}
}
function doPaste(control)
{
maxLength = control.attributes["maxLength"].value;
value = control.value;
if (maxLength)
{
event.returnValue = false;
maxLength = parseInt(maxLength);
var o = control.document.selection.createRange();
var iInsertLength = maxLength - value.length + o.text.length;
var sData = window.clipboardData.getData("Text").substr(0, iInsertLength);
o.text = sData;
}
}
function LimitInput(control)
{
if (control.value.length > control.attributes["maxLength"].value)
{
control.value = control.value.substring(0, control.attributes["maxLength"].value);
}
}
Now I created a test web page and added the control on the page as:
Aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %> <%@ Register TagPrefix="Custom" Namespace="CustomServerControls" %>