Reputation: 61
I want to set MaxLength property of a textbox with multiline in asp.net(for example 100 character). I do not want to use javascript solution. I have used :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" SetFocusOnError="true" ValidationExpression="^[a-zA-Z.]{0,100}$"></asp:RegularExpressionValidator>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Height="109px" Width="274px" ></asp:TextBox>
</div>
</form>
</body>
</html>
and this :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RegularExpressionValidator ID="rgConclusionValidator2" ControlToValidate="TextBox1" ValidationExpression="^[\s\S]{0,100}$" runat="server" SetFocusOnError="true" /></asp:RegularExpressionValidator>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Height="109px" Width="274px" ></asp:TextBox>
</div>
</form>
</body>
</html>
but none of them works. i have test on latest ie, firefox , chrome , opera. thanks alot.
Upvotes: 0
Views: 5632
Reputation: 146
Use this JavaScript function for maxlength and call it on OnKeypress.
function checktextarea(textvalue,message,limit)
{
var str="";
var str=textvalue.value;
if((str.length > limit ))
{
alert('Error : '+message + limit + ' characters\n'+ ' You entered text with Length '+str.length);
textvalue.focus()
return false;
}
else
{
return true;
}
}
Upvotes: 1
Reputation: 7504
It is working, but:
Validators won't validate on the fly - so it will allow you to enter anything, including rather long texts. It is not like maxlength
property which just won't allow you to enter more than 100 characters.
You need some action to start validation. In most cases it is button, so just add it:
<asp:Button runat="server" Text="OK" />
You need error message, which will be shown to user if validation fail - add ErrorMessage
property to validator:
<asp:RegularExpressionValidator ... ErrorMessage="ERROR!" />
And that's it - type text, click button, see error.
If you do want to restrict text length on the fly - then you need JavaScript, you can see this question for samples Specifying maxlength for multiline textbox
Upvotes: 1