If you ever try to set the MaxLength property of a MultiLine TextBox in ASP.NET, it won't work. It would seem to have no effect at all.
MaxLength Atrribute is not supported by the TextArea element
When an ASP.NET TextBox control is set to MultiLine mode, it is rendered as a TextArea HTML element. TextArea element do not support 'MaxLength' attribute, and therefore the TextBox won't render this attribute in MultiLine mode. It won't give you any warning or throw an error, but quietly ignore this property.
Solution
The first time I had a need to restrict length in a MultiLine TextBox, I quickly dropped a CustomValidator Control to take care of it. But later I realized a ReqularExpressionValidator could also be used for this purpose.
Here is the ValidationExpression to set the MaxLength (and also MinLength) of the input string: [^$]{MinLength,MaxLength}
Replace MinLength and MaxLength with numeric values. For example, a 100 character MaxLength with no Minimum length: [^$]{0,100}
Note:
A new line in MultiLine mode is considered two characters, because a new line is actually combination of two characters: CR and LF. I am not sure but on Unix/Linux based clients this may not be the case.
Afterthought
Ok, it seems many people end up here looking for a solution to this MaxLength property issue, and looking at the low ratings this post has received, I am assuming that some were not very happy with the above solution.
This post was originally meant to be for developers who would know how to use a RegularExpressionValidator and ASP.NET validation in general.
The behavior with a RegularExpressionValidator does not simulate the MaxLength property exactly because it does not prevent the user from entering further characters once the limit is reached, but rather integrates with the rest of validation framework and shows a friendly message to the user. To simulate the MaxLength property exactly, you could write a small Javascript snippet to trap the OnKeyPress event of the TextArea element and discard further keystrokes once the limit is reached.
Here is an example for keeping MaxLength to 100 characters:
onkeypress="if(this.value.length>=100) return false;"
You can add this straight into the TextBox tag. If javascript is disabled on the client browser, this will simply fail, and so you still need to validate it on server side.
I personally prefer the use of validation controls as it inherently validates both client side and server side.
The solution shown here could also be used with single line TextBox if you needed to ensure a minimum length of input.
Posted on September 15, 2007 03:44 by
Haider