maxlength for a multiline textbox
In asp.net you can set the attribute maxlength which works fine if the textmode is SingleLine, but if you set the textmode to MultiLine then maxlength no longer works.
This is because the html that is rendered is a textarea instead on a regular input field.
Customvalidator to the rescue!
For example:
<asp:TextBox runat="server" ID="txtIntro" TextMode="MultiLine" Rows="3" /> <asp:CustomValidator runat="server" ID="cvIntro" maxlength="255" ErrorMessage="Please enter 255 characters or less" ControlToValidate="txtIntro" ClientValidationFunction="checkTextAreaLength" />
This “fires” this clientside function:
<script type="text/javascript">
function checkTextAreaLength(source, arguments) {
var maxlength = $(source).attr("maxlength");
if (maxlength == undefined) maxlength = 255;
if (arguments.Value.length > maxlength)
arguments.IsValid = false;
else
arguments.IsValid = true;
}
</script>
One thing to note is that I’ve had to add the maxlength attribute to the customvalidator not to the textbox. I would prefer to have maxlength set on the textbox but so far I’ve been unable to work this out. If anyone has any ideas please let me know.
This entry was posted by nerdboy on Wednesday, March 17th, 2010 at 4:41 pm and is filed under asp.net. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response below, or trackback from your own site.