Friday, 24 September 2010

ASP.NET: Limiting the length of a multiline textbox

ASP.NET comes with a lot of nice validator controls which save you the hassle of writing a lot of JavaScript components yourself.

The TextBox control has a MaxLength property which allows you to easily restrict the length of the input. But bizarrely, a TextBox with its TextMode property set to MultiLine does not have this property.

But of course, you still need a way to limit the amount of text input or your database operations could fail.

Previously, I was using a JavaScript function attached to these textboxes with a function which was fired on keyup or lost focus which counted the number of characters and prevented overflow of a maximum set amount.

That's the long way of doing it though: you can achieve the same validation using a RegularExpressionValidator, as highlighted on this post by Raj Kaimal.

Fundamentally, you create a RegularExpressionValidator control, point it at your multiline textbox and set this as the RegEx (300 in this example obviously being the maximum number of characters allowed):


Et Voila! A simple and elegant solution - and no custom JavaScript required!