简体   繁体   中英

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?

使用MaxLength属性

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

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.

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

你的意思是MaxLength财产?

You can use the MaxLength property:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM