c# - ASP.NET MVC 2 client-side validation triggering incorrectly -
i using dataannotations enable client-side validation in asp.net mvc 2 project. having issue url validation regex passes unit test, fails in 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 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 have idea why passing unit test, failing when test view in browser?
i can see several problems regex, what's tripping comma in p=7,8
. regex doesn't match it, ismatch
doesn't require to; it's happy stopping @ 7
. guess client-side validator implicitly anchoring match. regex should anchored anyway; add ^
beginning , $
end, , should @ least consistent results. can change regex accommodate comma.
there's typo in regex: second f
in [a-fa-f\d]
should f
. and, although it's not error have \d
, \w
in same set of square brackets, redundant; \w
matches digits letters, can remove \d
(and [\w\d]
can reduced \w
). finally, {2,2}
should {2}
.
Comments
Post a Comment