Friday, March 30, 2012

Asp.Net - TextArea validation using RegularExpressionValidator

The Asp.Net TextArea control doesnot support the MaxLength property, though you set the MaxLength property, the TextArea control will not restrict the users to enter text within the set limit. The MaxLengh property works fine with the TextBox controls, but when it comes to TextArea controls (TextMode = MultiLine) the MaxLength property fails.

The RegularExpressionValidator, control can be used to validate the MaxLength property of the TextArea control. Her’s how this can be accomplished.

Add a TextBox control to your Asp.net form and set its TextMode property to MultiLine, then add a RegularExpressionValidator control with the regular expression to restrict the length of the text in the TextBox.

Here’s the code

<asp:TextBox id="txtProjectDescription"
runat="server"
CssClass="text"
MaxLength="2500"
Width="500px"
TextMode="MultiLine"
Rows="5">
asp:TextBox>

<asp:RegularExpressionValidator
ID="valtxtProjectDescription"
runat="server"
ControlToValidate="txtProjectDescription"
Display="None"
ErrorMessage="Project Description Should be less than 2500 Characters"
SetFocusOnError="True"
ValidationExpression="^([\S\s]{0,2500})$">
asp:RegularExpressionValidator>

Add the Save Button and the Validation Summery control

<asp:Button
ID="cmdSave"
runat="server"
Text="Save"
/>

<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter a text with length more that 2500 characters in the TextArea. You should get an error message

Project Description Should be less than 2500 Characters

That's it, we have implemented the MaxLength property for a TextArea control in Asp.net


Search Flipkart Products:
Flipkart.com

No comments: