I\'m trying to use asp:
I want a way to spe
Use a regular expression validator instead. This will work on the client side using JavaScript, but also when JavaScript is disabled (as the length check will be performed on the server as well).
The following example checks that the entered value is between 0 and 100 characters long:
<asp:RegularExpressionValidator runat="server" ID="valInput"
ControlToValidate="txtInput"
ValidationExpression="^[\s\S]{0,100}$"
ErrorMessage="Please enter a maximum of 100 characters"
Display="Dynamic">*</asp:RegularExpressionValidator>
There are of course more complex regexs you can use to better suit your purposes.
Have a look at this. The only way to solve it is by javascript as you tried.
EDIT: Try changing the event to keypressup.
This snippet worked in my case. I was searching for the solution and thought to write this so that it may help any future reader.
ASP
<asp:TextBox ID="tbName" runat="server" MaxLength="250" TextMode="MultiLine" onkeyUp="return CheckMaxCount(this,event,250);"></asp:TextBox>
Java Script
function CheckMaxCount(txtBox,e, maxLength)
{
if(txtBox)
{
if(txtBox.value.length > maxLength)
{
txtBox.value = txtBox.value.substring(0, maxLength);
}
if(!checkSpecialKeys(e))
{
return ( txtBox.value.length <= maxLength)
}
}
}
function checkSpecialKeys(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
@Raúl Roa Answer did worked for me in case of copy/paste. while this does.
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.
protected override void Render(HtmlTextWriter writer)
{
if (this.TextMode == TextBoxMode.MultiLine
&& this.MaxLength > 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.MaxLength.ToString());
}
base.Render(writer);
}
MaxLength
is now supported as of .NET 4.7.2, so as long as you upgrade your project to .NET 4.7.2 or above, it will work automatically.
You can see this in the release notes here - specifically:
Enable ASP.NET developers to specify MaxLength attribute for Multiline asp:TextBox. [449020, System.Web.dll, Bug]
use custom attribute maxsize="100"
<asp:TextBox ID="txtAddress" runat="server" maxsize="100"
Columns="17" Rows="4" TextMode="MultiLine"></asp:TextBox>
<script>
$("textarea[maxsize]").each(function () {
$(this).attr('maxlength', $(this).attr('maxsize'));
$(this).removeAttr('maxsize');
});
</script>
this will render like this
<textarea name="ctl00$BodyContentPlac
eHolder$txtAddress" rows="4" cols="17" id="txtAddress" maxlength="100"></textarea>