tags:

views:

136

answers:

2

I need to ensure that the input value contains at least one dot, so i use 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?

+1  A: 

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
A single backslash works as well:`alert('12.3'.match("\."));`
UserControl
@frogbot: You are right. I have updated with a better sample.
Jørn Schou-Rode
+1  A: 

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
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
I just tested it. It does. At least the one I use here on my webiste.
Jens
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
@Jens: 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
@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