Josh
Josh

Reputation: 8477

Regular Expression to test for the number of any characters in a range

I'm using the ASP Validation control a wanted to test that multiline textbox content was between 2 and 40 characters. Any character can be provided, including the new line character. What would be the expression? What I have below fails.

<asp:RegularExpressionValidator ID="RegularExpressionValidator" 
   runat="server"
   ValidationExpression="^[.]{2,40}$"
   ControlToValidate="CommentsTextBox"
   ErrorMessage="The Comment field must be between 2 and 40 characters" 
   Display="Dynamic">*</asp:RegularExpressionValidator>

Upvotes: 3

Views: 1042

Answers (2)

Alan Moore
Alan Moore

Reputation: 75222

When you put the dot inside square brackets, it loses its special meaning and just matches a literal dot. The easiest way to match any character in an ASP RegularExpressionValidator is like this:

^[\s\S]{2,40}$

[\s\S] is the standard JavaScript idiom for matching anything including newlines (because JS doesn't support DOTALL or s-mode, which allows the dot to match newlines). It works the same in .NET, so you don't have to worry about whether the dot matches newlines, or whether the regex will be applied on the server or the client.

Upvotes: 3

jasonbar
jasonbar

Reputation: 13461

You're treating the period as a literal inside the brackets. You just want:

^(.|\n){2,40}$

Upvotes: 1

Related Questions