Click here to Skip to main content
15,895,538 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi every one,

I have a textbox with mode as multiline. User should not enter more than 10 characters(string type) in it. So, for this i used maxlength=10. but still user is able to exceed this range. So, any validators to be used, or to be done by javascript. what is the reason behind, that maxlength does not work as i am using asp.net 2.0. plz give suggestions or code.

thanks
Posted

Use javascript to achieve this.

Google having some links,

http://www.google.co.in/search?q=maxlength+multiline+textbox+asp.net[^]

:)
 
Share this answer
 
This is a well known problem in ASP.NET

Standard Textbox controls when set to TextMode="MultiLine" means the MaxLength property does not work.

The following is the code that will restrict the text box to maximum of 10 characters.

XML
<asp:textbox id="txtComments" runat="server" textmode="MultiLine" height="100px" width="320px" maxlength="10"></asp:textbox>
<asp:regularexpressionvalidator id="regComments" runat="server" 
ControlToValidate="txtComments" ValidationExpression="^[\s\S]{0,10}$"
ErrorMessage="Maximum 10 characters are allowed in comments box."
Text="10chrs max" >
</asp:regularexpressionvalidator>
 
Share this answer
 
v4
Comments
Dalek Dave 24-May-10 5:51am    
Ankur
Did you change anything?
(Other than tidy up the appearance).
I tend to use a variation on this script
JavaScript
<script language="javascript" type="text/javascript">
  <!--
  function setMaxLength() {
        var x = document.forms[0].getElementsByTagName('textarea');
        for (var i=0;i<x.length;i++) {
        if (x[i]) {

              x[i].onkeyup = x[i].onchange = checkMaxLength;
              x[i].onkeyup();
        }
        }
  }

  function checkMaxLength() {
        var maxLength = 10;
        var currentLength = this.value.length;
        if (currentLength > maxLength)
        this.value = this.value.substring(0, maxLength);
  }
  //-->
</script>
Behind the scenes, ASP.NET converts a multi-line textbox into a text area, so you would run this script once the page has loaded (e.g. <body onload="javascript:setMaxLength();">). It has the advantage that it takes into account the case where somebody tries to paste text that would break your upper limit.
 
Share this answer
 

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