Home Search Member List Faq Register Login  
JavaScript Tips
Validate max character length in a text area

Thread Starter: Karamasoft   Started: 09-04-2007 7:08 PM   Replies: 0
 Karamasoft Support Forums » General Discussions » JavaScript Tips » Validate max character length in a text area
 Printable Version    « Previous Thread   Next Thread »
  04 Sep 2007, 7:08 PM
Karamasoft is not online. Last active: 5/8/2018 10:36:45 AM Karamasoft

Top 10 Posts
Joined on 09-05-2004
Posts 6,820
Validate max character length in a text area

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


  
 Page 1 of 1 (1 items)
Karamasoft Support Forums » General Discussions » JavaScript Tips » Validate max character length in a text area

You can add attachments
You can post new topics
You can reply to topics
You can delete your posts
You can edit your posts
You can create polls
You can vote in polls
Forum statistics are enabled
Forum is unmoderated

© 2002-2018 Karamasoft LLC. All rights reserved.