Using RegularExpressionValidator for Validating Maximum Length
<asp:TextBox
ID="txtDesc"
runat="server"
TextMode="MultiLine"
placeholder="Enter Description [Max 50 Chars.]"
Width="300px">
</asp:TextBox>
In the above markup, I am using an Asp.Net "textbox" element with its TextMode set as "MultiLine". The textbox must accept only 50 characters only.
Using a RegularExpressionValidatory control, I can check the number of characters the user entered, at client side itself. Here’s how you should do it …
<asp:RegularExpressionValidator
runat="server"
ID="validate"
ControlToValidate="txtDesc"
ValidationExpression="[\s\S]{0,50}"
ErrorMessage="Please enter a maximum of 50 characters"
ForeColor="red">
</asp:RegularExpressionValidator>
The above validator control will check if the input is between 0 and 50 characters long. I have defined the length inside curly braces { }. The two other MetaCharacters inside the square box [ ] will check for white-space characters (\s) and non white-space characters (\S).
Ref: Regular Expressions in Asp.Net