asp.netregexreg-expressionvalidator

Backslash escaping in RegularExpressionValidator


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?


Solution

  • 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.