10

I've bee searching for a way to limit the text within a TextBox which looks like this

<asp:TextBox runat="server" ID="tbTest" TextMode="MultiLine" MaxLength="20" Rows="5" Columns="30" > </asp:TextBox> 

The property MaxLength="20" only works if the other property TextMode="MultiLine" is not set. It isn't even rendered.

The output in the HTML looks like this:

<textarea name="ctl00$ContentPlaceHolder1$tbTest" id="ctl00_ContentPlaceHolder1_tbTest" rows="5" cols="30"> </textarea> 

If you search here on SO for a solution to solve this issue, you get 2 ways suggested:

  • add a (asp:RegularExpression) validator and validate the control
  • add a JavaScript which removes the last insert character in case the limit is reached.

BUT

Most of the answer are previous 2013 and the support of maxlength over all browsers was from 2013 as IE10 was released (reference).

Currently every Browser supports this attribute - test it on your own: https://jsfiddle.net/wuu5wne1/

QUESTION

How can I force ASP.Net to apply this attribute to my multiline textbox?

4
  • I don't think there was much change in current browsers. You still have to work with JS or a regexp. Commented Feb 16, 2017 at 6:50
  • 3
    I think if you add MaxLength Attribute from Code Behind it will work, or use html <textarea> and in code behind access the value of textarea Commented Feb 16, 2017 at 7:01
  • @ManishGoswami <textarea> has any disadvantages compared to asp:TextBox? Commented Feb 16, 2017 at 7:06
  • so you can try first option..setting attribute from code behind.there is still one option is open use jquery/javascript/Regular Expression Commented Feb 16, 2017 at 7:09

3 Answers 3

12

Welcome to 2020 - this one finally works now on all Browsers

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { tbTest.Attributes.Add("maxlength", "20"); } } 
Sign up to request clarification or add additional context in comments.

Comments

5

My solution to this was to just manually set the maxlength property via jquery in document.ready:

$(document).ready(function () { $('#<%=tbTest.ClientID%>').prop('maxlength', 20); } 

Yeah, it's a bit hacky, but if you want to use the asp control (I didn't want to have to deploy a code change), it works.

Comments

0

In Visual Studio 2019, maxLength will work if you add columns property

<asp:TextBox runat="server" Columns="1" MaxLength="50" class="form-control" ID="txtFirstName" ClientIDMode="Static" required /> 

1 Comment

Not working here. <asp:TextBox TextMode="MultiLine" ID="c_pasteptherapy" Columns="1" MaxLength="100" runat="server" ></asp:TextBox>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.