HTML input type of text element provides a built-in MaxLength property to set the
maximum number of characters that the user can enter. However, the TextArea
element does not have such property to limit the number of characters that can be
entered. When you have an ASP.NET TextBox control with TextMode="MultiLine" in
your web page, it is rendered as an HTML TextArea element and you cannot use
MaxLength property to set the maximum number characters.
What you can do is to define a keypress event handler for the TextBox control to
check the length of the text inside the text area and cancel the event if the
MaxLength is reached.
JavaScript
function ValidateMaxLength(evnt, str, maxLength)
{
var evntKeyCode = GetEventKeyCode(evnt);
//Ignore keys such as Delete, Backspace, Shift, Ctrl, Alt, Insert,Delete, Home, End, Page Up, Page Down and arrow keys
var escChars = ",8,17,18,19,33,34,35,36,37,38,39,40,45,46,";
if (escChars.indexOf(',' + evntKeyCode + ',') == -1)
{
if (str.length >= maxLength)
{
alert("You cannot enter more than " + maxLength + "
characters.");
return false;
}
}
return true;
}
ASPX
<asp:TextBox ID="txtValidateMaxLength" runat="server"
TextMode="MultiLine" />
C#
protected void Page_Load(object sender, EventArgs e)
{
txtValidateMaxLength.Attributes.Add("onkeypress", "return
ValidateMaxLength((window.event) ? window.event : arguments[0],this.value, 5)");
}
0 comments:
Post a Comment