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);
}
};

2 comments:

Unknown said...

Max length just returns or sets the greatest number of characters in a textbox. On the off chance that you set it to 3, at that point individuals will, in any case, have the option to enter any number up to. Assignment Writing Help You have to change over the content to a whole number and test that.

saramartin said...

Asp .net is Part of Visual fundamental lang and it is a specialist of Web website program And the client name and secret word it is default I thing the client name is root and the secret key is administrator or root Dianna Agron Black Leather Jacket ......again and on the off chance that you don't plan of site uninstall it.