Home > ASP.Net, Javascript > Validate TextBox Max Length

Validate TextBox Max Length


Hi

try this javascript function

<script language="javascript">

function textCounter(field, maxlimit) {
if (field.value.length > maxlimit)
{
 alert ("You have reached 500-character limit.");
 field.value = field.value.substring(0, maxlimit);
}
else // otherwise, update 'characters left' counter
{
 //countfield.value = maxlimit - field.value.length;
}
}

</script>

You can use it this way:

<asp:TextBox ID="txtComments" Rows="15" runat="server"
 TextMode="MultiLine"
 Columns="75"
 ToolTip="Insert your Text Here"
 onKeyDown="textCounter(this.form.txtComments,500);"
 onKeyUp="textCounter(this.form.txtComments,500);" />

or try this example using RegularExpressionValidator control

<asp:TextBox ID="txtExample" runat="server" TextMode="MultiLine" />
<asp:RegularExpressionValidator ID="revExample" runat="server"
ControlToValidate="txtExample" ValidationExpression="[\s\S]{1,200}"
Display="Dynamic" ErrorMessage="Length cannot be greater than 200 characters"/>

Good Luck

Advertisements
Categories: ASP.Net, Javascript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: