Quick Character Limiter on MultiLine TextBox Control

September 10, 2010

The .Net TextBox control has a ‘MaxLength’ property – This of course is a handy and effective way of limiting the number of characters entered (although bear in mind this is client side only – You should back it up with a server-side check).

The ‘MaxLength’ attribute does not work with multi line text boxes (TextMode=”MultiLine”). This is because the TextBox control is then rendered as a ‘TextArea’ HTML control, which does not support the max length property.

Clearly it is important to check/limit the number of characters the user enters as this could pose a security threat, and more likely cause annoying ‘String or binary data would be truncated’ errors as the system tries in vain to squeeze 300 characters into a VarChar(200) database column.

So – What to do? Options:

a) Check server-side, if too long warn the user on a label and do carry out required action

b) Use a javascript visual count-down, coupled with a server-side check

c) Use ASP.Net regular expression validator

My personal favourite has always been option B – But project deadlines mean I don’t always have time to put this in place.

Option C is effective, secure and fast:

<asp:TextBox ID="TextBoxAddToClipboardNotes" runat="server" TextMode="MultiLine" Height="50" />
<asp:RegularExpressionValidator ID="RegExValidatorTextBoxAddToClipBoardNotes" runat="server" ControlToValidate="TextBoxAddToClipBoardNotes" ValidationExpression="^[\s\S]{0,1000}$" Text="Notes can be no more than 1000 characters" />

TheValidationExpression of ^[\s\S]{0,1000}$ means allow between 0 and 100 of any character (Lowercase – \s or Uppercase – \S). Anything else fails to match, which fires the validation control, showing a client side error – Like all ASP.Net validation controls (Apart from the custom validator – This is developer choice) This will also check serverside.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: