Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

How do i limit the number of characters a user can type in a textbox?

I want to limit the number of characters a user can type in a textbox (say no more than 100 characters). How can i achieve that?

Upvotes: 2

Views: 6011

Answers (5)

Pathum Chamara
Pathum Chamara

Reputation: 105

You can use the MaxLength property:

<asp:TextBox ID="zoneTextBox" runat="server" Height="23px" 
             onkeypress="CallToButton();"
             Width="89px" MaxLength="1"></asp:TextBox>

Upvotes: 0

V4Vendetta
V4Vendetta

Reputation: 38230

Javascript would be your best bet in case you have Multiline textbox

function IsMaxLength(obj, MaxLen)
{
  return (obj.value.length <= MaxLen);
}

and attach this to the Textbox

onkeypress="return IsMaxLength(this, 100);"

else for the normal one as the others have suggested setting Maxlength would suffice

Upvotes: 3

ChrisF
ChrisF

Reputation: 137188

Use the MaxLength property

<asp:TextBox ID="Value1" MaxLength="100" runat="server"/>

Upvotes: 6

Pleun
Pleun

Reputation: 8920

Do you mean the MaxLength property?

Upvotes: 2

Tom Robinson
Tom Robinson

Reputation: 8528

You can use the MaxLength property.

This results in HTML something like this:

<input type="text" name="name" maxlength="100" />

However, it's worth mentioning that this is only validated on the client-side and is easy to bypass. You should also validate it on the server-side, by checking the Length of the TextBox.Text property.

Upvotes: 5

Related Questions