Click here to Skip to main content
15,906,463 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to limit a textbox with only 50 characters.

ie, user can only enter only 50 characters.

Please help
justinonday 4-Feb-11 4:57am    
<asp:TextBox ID="TextBox1" MaxLength="50" runat="server"></asp:TextBox>

Share this answer
Ankur\m/ 4-Feb-11 5:04am    
Correct answer! :)
Sandeep Mewara 4-Feb-11 5:13am    
Yes it is, but would not be sufficient for all scenarios.
Ankur\m/ 4-Feb-11 5:26am    
Can you give an example? AFAIK, it works even if JavaScript is disabled.
Espen Harlinn 6-Feb-11 11:14am    
Nice and simple
If you are using a multiline textbox see here[^].
Share this answer
Espen Harlinn 6-Feb-11 11:14am    
Good link, interesting article :)
I guess while 'pasting' anything of more than 50 would allow textbox have it even if you have maxlength property set.

Have a look at this approach:
Setting Maxlength via Javascript[^]
Check maxlength of multiline textbox in javascript[^]
Share this answer
Coding C# 4-Feb-11 5:10am    
I think its not while 'pasting', its while setting from code behind it will allow textbox to have text more than maxlength limit.

However its correct that maxlength won't work in case of multiline textbox, need to use javascript/jquery.
Sandeep Mewara 4-Feb-11 5:12am    
As much I remember, it's while pasting too.
Coding C# 4-Feb-11 5:19am    
I just tried and it doesn't while pasting...
Sandeep Mewara 4-Feb-11 5:23am    
Ok. Thanks for confirming. It must be pasting in Multiline.
Ankur\m/ 4-Feb-11 5:28am    
Your code will fail if JavaScript is disabled. But Maxlength property works for disabled JavaScript as well. Moreover it will work even if you paste a string having length greater than defined length by concatenating the string.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900