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

    placeholder="Enter Description [Max 50 Chars.]" 

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 …

    ErrorMessage="Please enter a maximum of 50 characters"

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

Hope you find this example useful. Happy coding. 🙂

← PreviousNext →