1

I need to ensure that the input value contains at least one dot, so I have used the following:

<asp:RegularExpressionValidator runat="server" 
ControlToValidate="MyInput" Text="*" 
ErrorMessage="must contain at least one dot" 
ValidationExpression="\.+" />

And that doesn't work. By inspecting the page source i can see that ASP.NET escapes the backslash character so in java-script it looks like "\\.+". Why does it do so and how do i prevent RegularExpressionValidator from escaping it?

captainsac
  • 2,484
  • 3
  • 27
  • 48
UserControl
  • 14,766
  • 20
  • 100
  • 187

2 Answers2

1

The double escape is necessary because the backslash is used for escape sequences in both JavaScript and regular expressions. A quick test to illustrate this point:

alert('42'.match("\d"));     // no match
alert('42'.match("\\d"));    // match

But that does not solve your problem. First step in troubeshooting: change the validation expression to a. Does it not fail on "foo" and pass on "bar"? If not, something else is wrong on your page - possibly an unrelated JavaScript bug causes the validation code to be skipped.

Slightly off topic: Your validation expressions can be trimmed to \. (without the plus), as you really only care about matching a single dot.

Jørn Schou-Rode
  • 37,718
  • 15
  • 88
  • 122
1

If you want to check if the input contains at least one dot, your expression is incorrect. It matches only input that consist only of dots.

You should use

.*\..*

If escaping proves to be a problem, too, use [.] instead of \..

Note that the RegularExpressionValidator does not validate empty fields. Use the RequiredFieldValidator to do this.

Jens
  • 25,229
  • 9
  • 75
  • 117
  • Are you sure that the `RegularExpressionValidator` implicitly searches for start and end of string? AFAIK it does *not*, hence `\.` should be a sufficient pattern. – Jørn Schou-Rode Mar 16 '10 at 09:59
  • I just tested it. It does. At least the one I use here on my webiste. – Jens Mar 16 '10 at 10:00
  • Thanks! That means that default JS regexp options are different from .NET Regex class, because the latter works fine. That is strange - if we have JS disabled RegularExpressionValidator should use server-side check (i.e. Regex class), shouldn't it? – UserControl Mar 16 '10 at 10:02
  • I stand corrected, then. But why on earth is the control implemented in that way? (Rethorical question, I do not expect you to know the answer.) – Jørn Schou-Rode Mar 16 '10 at 10:08
  • @Jørn: I guess the control if designed to check things like zip codes, credit card numbers and such. You'd need an exact match more often. – Jens Mar 16 '10 at 10:29