I am using DataAnnotations to enable client-side validation in an ASP.NET MVC 2 project. I am having an issue where my URL validation regex passes my unit test, but it fails in the actual website.
Model
[RegularExpression(UrlValidation.Regex, ErrorMessage = UrlValidation.Message)]
public string Url { get; set; }
Regex = "(([\w]+:)?//)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?"
Message = “Invalid Url”
View
<div class="editor-label">
<%: Html.LabelFor(model => model.Url) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Url) %>
<%: Html.ValidationMessageFor(model => model.Url) %>
</div>
Result With URL = http://www.chicagoshakes.com/main.taf?p=7,8

Passing Unit Test
[Test]
public void GetVarUrlPasses()
{
var url = "http://www.chicagoshakes.com/main.taf?p=7,8";
var regex = new Regex(UrlValidation.Regex);
Assert.IsTrue(regex.IsMatch(url));
}
Does anyone have any idea why this is passing the unit test, but failing when I test the view in a browser?
Alan Moore was basically right, the regex was junk. I ended up using a this regex.
Also, here’s the proper way to write the unit test: