Tom Hamming
Tom Hamming

Reputation: 10961

Use a RegularExpressionValidator to allow one of two patterns at the beginning of input

I've got a RegularExpressionValidator (ASP.NET 2.0) that I'm using to make sure that a URL entered in a text box begins properly with http://. I was using a ValidationExpression of ^http://. Now I'm allowing mailto links as well, so my expression is ^http://|^mailto:.

It works in a regex tester (set to Client-side Javascript engine) for inputs like "http://www.google.com" and "mailto:[email protected]". But the RegularExpressionValidator on my page doesn't let any valid inputs through.

I've tried the following variations, all of which work in the tester but none of which work in the validator:

The declaration of the validator is this:

<asp:RegularExpressionValidator ID="revEditUrl" runat="server"
   ControlToValidate="txtEditUrl" ErrorMessage="Url must begin with 'http://' or 'mailto:'"
   ValidationExpression="^((http://)|(mailto:))" Display="Dynamic"
   ValidationGroup="myGroup" />

My intent is to allow any input that begins with either http:// or mailto:. What am I doing wrong here?

UPDATE: The MSDN page on Regular Expressions in ASP.NET says:

You do not need to specify beginning of string and end of string matching characters (^ and $)—they are assumed. If you add them, it won't hurt (or change) anything—it's simply unnecessary.

Does this mean that it's assuming that my input can't have anything in it that doesn't conform to my regex (i.e. that it should be either http:// or mailto:)? If so, then why did my original pattern of ^http:// work?

Upvotes: 0

Views: 2157

Answers (2)

user849425
user849425

Reputation:

You have to escape :: and /.

Also, I wonder if RegularExpressionValidator doesn't automatically presume that the whole string matches and implies $ at the end. Try:

^((http\:\/\/)|(mailto\:))(.+)$

Upvotes: 1

aparker
aparker

Reputation: 178

Try escaping every non-alphanumeric character, one at a time, including the parantheses. I imagine its just one of those - every regex implementation has different characters that are metacharacters by default.

Upvotes: 0

Related Questions