Fix MaxLength property for ASP.NET Multiline Textbox

If you try to change the TextMode property of ASP.NET TextBox control to Multiline and set the MaxLength property it’ll not work and user can insert as much characters as he/she want. WHY? Because when you put TextBox in your WebForm it’ll be rendered to HTML <input> tag but when you set the TextMode to multiline it’ll be rendered to <textarea> tag, and MaxLength attribute is in <input> but it’s not for <textarea>.

So dude How can I solve this issue?

From my opinion it’s better to solve this by using JavaScript function than using RegularExpressionValidator, so let’s write the JavaScript function and call it in onKeyPress TextBox client event.

JavaScript function
  1.         function textboxMultilineMaxNumber(txt, maxLen) {
  2.  
  3.             if (txt.value.length > (maxLen – 1)) return false;
  4.             else {
  5.                 return true;
  6.             }
  7.         }

MultiLine TextBox
  1. <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"
  2.     onkeypress="return textboxMultilineMaxNumber(this,15);">
  3.     </asp:TextBox>

As you can see in line number 2 I pass TextBox and MaxLength, this will make the max number of characters user can input in the MultiLine TextBox is 15.

Tagged on: ,
  • George

    So, if someone turns off Javascript in their browser, they get to input as much text as they like? RegularExpressionValidator does validation both client side and server side – it’s a much better solution.

    • EmadMokhtar

      First let me thank you for suggesting a better solution. I write this solution consider none will disable JavaScript in browser, I even don’t know why anyone will do this, anyway thanks @adfd8fee55be3fe7e9a2f4da0cf4ae41:disqus

  • Grid

    Thanks, Emad. This is great.
    Also found another great way around the problem directly through .net code rather than javascript:
    http://stackoverflow.com/a/18072320/2536576