views:

33

answers:

2

I have a URL validation method which works pretty well except that this url passes: "http://". I would like to ensure that the user has entered a complete url like: "http://www.stackoverflow.com".

Here is the pattern I'm currently using:

"^(https?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@ 
+ @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184 
+ "|" // allows either IP or domain 
+ @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www. 
+ @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // second level domain 
+ "[a-z]{2,6})" // first level domain- .com or .museum 
+ "(:[0-9]{1,4})?" // port number- :80 
+ "((/?)|" // a slash isn't required if there is no file name 
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"

Any help to change the above to ensure that the user enters a complete and valid url would be greatly appreciated.

+1  A: 

Why not use a urlparsing library? Let me list out some preexisting url parsing libraries for languages:

Ask if I'm missing a language.

This way, you could first parse the uri, then check to make sure that it passes your own verification rules. Here's an example in Python:

url = urlparse.urlparse(user_url)
if not (url.scheme and url.path):
    raise ValueError("User did not enter a correct url!")

Since you said you were using C# on asp.net, here's an example (sorry, my c# knowledge is limited):

user_url = "http://myUrl/foo/bar";
Uri uri = new Uri(user_url);
if (uri.Scheme == Uri.UriSchemeHttp && Uri.IsWellFormedUriString(user_url, UriKind.RelativeOrAbsolute)) {
    Console.WriteLine("I have a valid URL!");
}
Mike Axiak
Thanks, Mike. I'm using c# (asp.net MVC 2). Most of my validation is done off the aspx page in classes.
fynnbob
A: 

This is pretty much a FAQ. You could simply try a search with [regex] +validate +url or just look at this answer: What is the best regular expression to check if a string is a valid URL

splash
Thanks, splash. After digging through your first link (the second one had the same problem I'm having) I found this post that did the trick: http://stackoverflow.com/questions/3546203/validate-url-in-form-http-www-test-com (see Amir's answer). I did some preliminary testing and so far so good.
fynnbob