Wednesday 4 July 2007

How to Set the Maximum Length of a MultiLine TextBox

The MaxLength property of a TextBox control has no effect when the TextMode is set to MultiLine. The reason for this is that a MultiLine TextBox is rendered as a <textarea> tag, which does not have a maximum length attribute:

<textarea name="txtComments" rows="2" cols="20" id="txtComments">

In contrast, a TextBox with its TextMode set to SingleLine is rendered as an <input> tag, which has the maxlength attribute:

<input name="txtComments" type="text" maxlength="5" id="txtComments" />

If you wish to restrict the amount of text in a MultiLine TextBox, the workaround is to use a RegularExpressionValidator control. In the following example, the validation expression allows between 0 and 5 alphanumeric characters to be entered:

string strMaxLength = "5";

revComments.ValidationExpression = "\\w{0," + strMaxLength + "}$";

No comments: