开发者

Backslash escaping in RegularExpressionValidator

I need to开发者_JS百科 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜