I've bee searching for a way to limit the text within a TextBox wich 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 fo a solution to solve this issue, you get 2 ways suggested:
asp:RegularExpression
) validator and validate the controlBUT
Most of the answer are prevois 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?
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");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With