I'm trying to use asp:
<asp:TextBox ID="txtInput" runat="server" TextMode="MultiLine"></asp:TextBox>
I want a way to specify the maxlength
property, but apparently there's no way possible for a multiline textbox
. I've been trying to use some JavaScript for the onkeypress
event:
onkeypress="return textboxMultilineMaxNumber(this,maxlength)"
function textboxMultilineMaxNumber(txt, maxLen) {
try {
if (txt.value.length > (maxLen - 1)) return false;
} catch (e) { }
return true;
}
While working fine the problem with this JavaScript function is that after writing characters it doesn't allow you to delete and substitute any of them, that behavior is not desired.
Have you got any idea what could I possibly change in the above code to avoid that or any other ways to get round it?
Here's how we did it (keeps all code in one place):
Just in case someone still using webforms in 2018..
Use HTML textarea with
runat="server"
to access it in server side. This solution has less pain than using javascript or regex.Note: To access
Text
Property in server side, you should usetxt1.Value
instead oftxt1.Text
Things have changed in HTML5:
ASPX:
C#:
Rendered HTML:
The metadata for
Attributes
:Another way of fixing this for those browsers (Firefox, Chrome, Safari) that support maxlength on textareas (HTML5) without javascript is to derive a subclass of the System.Web.UI.WebControls.TextBox class and override the Render method. Then in the overridden method add the maxlength attribute before rendering as normal.
I tried different approaches but every one had some weak points (i.e. with cut and paste or browser compatibility). This is the solution I'm using right now:
In this case, I'm calling multilineTextBoxKeyUp on key up and multilineTextBoxKeyDown on key down:
try this javascript:
On the control invoke it like this:
You could also just use the checkSpecialKeys function to validate the input on your javascript implementation.