开发者

Regex for validating a website address in ASP.NET

When I use a regex validator on a page with the following regular expression:

<asp:RegularExpressionValidator ID="regexWebsiteValidator" runat="server" ControlToValidate="ctlWS" ValidationExpression="(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?" ErrorMessage="Invalid Website Address!" />

and enter http://www,google.com in the textbox, the validation fails as expected.

If I use the same regex but try to match it using Regex.Match, it passes. Can someone tell me what I am doing wrong?

string strRegex = @"(http(s)?开发者_StackOverflow://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?";
bool b = System.Text.RegularExpressions.Regex.Match("http://www,google.com", strRegex).Success;

b is true!


For one thing, you are not anchoring your expression using ^(regex goes here)$. What is happening here is that it is successfully matching the "google.com" part. The RegularExpressionValidator control probably adds these anchors implicitly—I don't know offhand because I never use the things.

In order to help you debug this further, make use of the Match.Value property so you can see exactly what is being matched.

More importantly, though, don't use regular expressions to validate URLs. There is a Uri class in .NET already. Use it's Parse method.


I'm not a Regex expert by any stretch of the imagination but it doesn't look like you're escaping the slashes in your strRegex variable as you've got the @ sign at the beginning of the declaration

Try something like :

string strRegex = @"(http(s)?://)?([\\w-]+\\.)+[\\w-]+(/[\\w- ;,./?%&=]*)?";
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜