Thursday, 20 December 2007

Golden Oldie - ASP.NET multiline doesn't enforce MaxLength property

This one is a Golden Oldie and is a problem with the Textarea HTML control (not specifically a problem with ASP.NET). Technically, the ASP.NET controls should not even provide the MaxLength property when TextMode is set to MultiLine....

But there are ways around this issue using javascript and/or inherited controls:


using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LendLease.MRP.Web.UI.WebControls
{
//Custom TextBox - used to fix issue with the Maxlength not working in controls
//modified version of http://www.codeproject.com/KB/aspnet/Extended_ASPNET_TextBox.aspx
public class TextBox : System.Web.UI.WebControls.TextBox
{

protected override void OnPreRender(EventArgs e)
{
if (MaxLength > 0 && this.TextMode == TextBoxMode.MultiLine)
{
if (!Page.ClientScript.IsClientScriptIncludeRegistered("TextArea"))
{
Page.ClientScript.RegisterClientScriptInclude("TextArea", ResolveUrl("~/Include/TextBoxMaximumLength.js"));
}
this.Attributes.Add("onkeyup", "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);
}
}
}


JAVASCRIPT:


function 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 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;
}
}
function LimitInput(control)
{
if(control.value.length > control.attributes["maxLength"].value)
{
alert("You cannot enter more than " + control.attributes["maxLength"].value + " characters into this field");
control.value = control.value.substring(0,control.attributes["maxLength"].value);
}
};

No comments: