tags:

views:

40

answers:

2

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>
+1  A: 

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

^(.|\n){2,40}$
jasonbar
Keep in mind that this will count the `\n` as 2 characters. So if you have a 40 character limit on a multi-line textbox, the user maybe only be able to enter 38 characters if an `\n` exists. Also if they just enter a carriage return (`\n`) and nothing else, the lower limit of 2 character will also pass even though no text was actually entered.
Kelsey
@Kelsey: Isn't it rather that pressing `Enter` in the textbox inserts a carriage-return *and* a linefeed (CRLF)? So the `.` matches the CR and `\n` matches the LF; nothing's being counted twice.
Alan Moore
Good point on the new line counting as 2 chars
Josh
+1  A: 

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.

Alan Moore
Good point on JavaScript support, since this test is run client and server side I'm going with this approach.
Josh