5

I try to restrict user input to specific number of characters in asp:textbox TextMode="MultiLine" using MaxLength property. But it's not working. What are the tweaks to get this solve?

<asp:TextBox ID="txtComment" runat="server" Width="90%" class="form_txtnormal" TextMode="MultiLine" Rows="1" MaxLength="250"></asp:TextBox>
Nishantha
  • 6,065
  • 6
  • 33
  • 51
  • 1
    possible duplicate of [Specifying maxlength for multiline textbox](http://stackoverflow.com/questions/1334286/specifying-maxlength-for-multiline-textbox) – Sam Nov 26 '14 at 05:20
  • 1
    refer this http://www.codeproject.com/Articles/158958/Why-MaxLength-property-of-a-textbox-with-multiline – Sain Pradeep Nov 26 '14 at 05:21

3 Answers3

3

Use JavaScript or RegularExpression to validate the length. Once you make the TextBox a MultiLine TextBox the max length is irrelevant, because it becomes a TextArea instead of an inputbox.

Here's an example

Community
  • 1
  • 1
Sam
  • 2,917
  • 1
  • 15
  • 28
  • as far as i know textarea admit maxlenght attribute and it normally work. Only on asp net pages is not working. – Andrea_86 May 31 '23 at 08:55
2

Got this solved.

My Textbox is dynamically created in Gridview so I add this attribute in Itembound event for the Grid.

protected void grdAreaOfEvaluation_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item.ItemIndex > -1)
    {
         TextBox txtComment = (TextBox)(e.Item.FindControl("txtComment"));
         txtComment.Attributes.Add("maxlength","250");
    }
}

This will also work in Page Load event if you are not create Textbox dynamically. I didn't check this.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
         txtComment.Attributes.Add("maxlength","250");
    }
}
Nishantha
  • 6,065
  • 6
  • 33
  • 51
1

When you are in Multiline TextMode, MaxLength has no effect on that TextBox control. So instead of that your are suppose to use a client side validation that will check your input string length on every keypress and restrict you from typing extra characters when your input exceeds maximum length using event.preventDefault() that restricts the default behavior of that keypress event. (You can also go with regular expression as mentioned in other answer)

Add this script in the head section :

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
    $(document).ready(function () {
        $("#txtComment").on("keypress", function (e) {
            if ($(this).val().length == 250) {
                e.preventDefault();
            }
        });
    });
</script>

Note : If you want to add this validation script to multiple controls then mark all the controls with same class name and in your script replace the id of the control with that class name for all controls.

References : .keypress() , event.preventDefault()

Md Ashaduzzaman
  • 4,032
  • 2
  • 18
  • 34