How to Use Regular Expression in Asp.Net to Validate TextBox for Maximum Length

← PrevNext →

You can use Regular expressions in Asp.Net to validate texts for either searching patterns or restricting user input in a textbox. If you are using a textbox in Asp.Net, you can use the MaxLength property to restrict user input for a maximum length. However, the MaxLength property does not work if you have set the TextMode of the textbox to MultiLine. Here in this post, I’ll show you how to apply regular expression on a textbox element, with MultiLine option, to check or validate maximum length.

Validate multiline textbox for Max length using Regular Expression

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

← PreviousNext →