Friday, December 16, 2011

MaxLength property of a textbox with multiline mode doesn't work. Reason and solution

When a Textbox is in SingleLine mode, it gets rendered as a input type text  and when it is in MultiLine mode, it gets rendered as a textarea. 
As we know MaxLength property works only for input type. Thats why MaxLength property doesn't works with Textbox with multiline property
So We have many custom solution for this.
but the best solution is using
Regular expression validator for this, which will check the count of the entered character and will throw an error if it exceeds. We need to have a regular expression that will work. Let's see the code

<asp:TextBox ID="tb" 
runat="server" 
TextMode="MultiLine" >
</asp:TextBox>
//Regular Expression validator
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" 
runat="server" 
ControlToValidate="tb" 
ErrorMessage="Please enter maximum 10 charachters."
                                SetFocusOnError="true" 
ValidationExpression="^[a-zA-Z.]{0,10}$">
</asp:RegularExpressionValidator>


Note: We have used a regular expression ^[a-zA-Z.]{0,10}$, which allows all the characters with length 0 to 10.

No comments:

Post a Comment

Total Pageviews