Tim Maxey .NET Technology Blog & Resources

MaxLength not working in ASP.NET textbox multiLine

Great code I found for maxlength issue with .NET textboxes. .NET textboxes, if TextMode is set to MutilLine, the maxlength property just doesn't work, sux. So after playing around with different soloutions. I found this on, thanks to a guy named "Leo." So a big thanks to him!

Add this function in JavaScript on your page, I stuck it my "functions.js" file I include on the page anyway.

function checkMaxLen(txt,maxLen) {
try{
if(txt.value.length > (maxLen-1)) {
var cont = txt.value;
txt.value = cont.substring(0,(maxLen -1));
return false;
};
}catch(e){
}
}

Then on the textbox use something like  this:

<asp:TextBox runat="server" ID="txtComments" CssClass="comment_textbox" Height="75px" TextMode="MultiLine" onkeyup="return checkMaxLen(this,151)"></asp:TextBox>

Notice the function passes the textbox (this) and the maxlength you want, in this case 150, notice I have 151, the function will limit the maxlength minus one... So if you want to limit the textbox with mutiline set to 100, you enter 101, make sense?


Feedback

# re: MaxLength not working in ASP.NET textbox multiLine

Gravatar Thanks a lot, your solution works perfect. 4/17/2009 4:48 AM | Sibusiso

# re: MaxLength not working in ASP.NET textbox multiLine

Gravatar This is just the information I was looking for. Great resource, site bookmarked. 5/15/2009 10:52 AM | Coupon Codes

# re: MaxLength not working in ASP.NET textbox multiLine

Gravatar Thanks! very nice.. :D 8/20/2009 3:13 AM | Ati

# re: MaxLength not working in ASP.NET textbox multiLine

Gravatar Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post. Keep up your work… 5/19/2010 3:30 AM | IT Outsourcing

Post a comment





 

Please add 6 and 3 and type the answer here: