Introduction
It is commonly known that the MaxLength
attribute does not work for textboxes with the TextMode
property set to MultiLine
since they are rendered as <textarea>
HTML controls, which miss this property.
There are lots of great articles around to solve this, but using custom controls etc., is too time expensive for larger projects.
This approach iterates through all the controls in a page (or other container controls) and attaches a JavaScript to all multiline textboxes to enable length validation. It works with AJAX / ATLAS, FormViews, and all commonly known browsers.
How to use
Add multiline textboxes to your page by setting the MaxLength
property. Now, all you have to do is use one line of code...
For performing length validation on all multiline textboxes on a page:
Put TextAreaValidator.CheckMaxLength(this);
inside the page's Page_Load
function.
For performing length validation on a specific textbox:
Put TextAreaValidator.CheckMaxLength(theTextBox);
inside the page's Page_Load
function.
For FormViews (also inside ATLAS UpdatePanels), use the FormView's OnItemCreated event with:
TextAreaValidator.CheckAllMaxLengthsWithinParentControl((FormView)sender)
, since the container controls are created at runtime and previously inaccessible.
Enjoy...