Click here to Skip to main content
13,835,319 members
Rate this:
 
Please Sign up or sign in to 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
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Use javascript to achieve this.

Google having some links,

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

:)
   
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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.

<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>
   
v4
Comments
Dalek Dave 24-May-10 5:51am
   
Ankur
Did you change anything?
(Other than tidy up the appearance).
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

I tend to use a variation on this script
<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.
   

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web05 | 2.8.190114.1 | Last Updated 24 May 2010
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100