Reputation: 348
I have a scenario for a hyperlink control, where user can provide either URL(http://:85/UI/FormRenderer) or URL with some file path (http://:85/UI/FormRenderer/Content/images/Close.png) . I need to validate for proper URL when URL is given, and need to validate for proper URL with file path when file path is provided, Currently I am struck with distinguishing between URL and URL with file path. Below is what I tried:
private static bool ValidateURL(string url)
{
bool stat = false;
var matURL = Regex.Match(url, @"^(https?|ftp|file)://.+$");
Match matFileType=null;
if(matURL.Success)
matFileType = Regex.Match(url, @"^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$");
if (matFileType != null)
stat = matFileType.Success;
else
stat = false;
return stat;
}
Upvotes: 0
Views: 2472
Reputation: 2293
Do you really need a regex? In C#, you could use the Uri class for validating the urls in general. For example, the following two will work:
new Uri("http://blahblah");
new Uri("https://localhost");
These three will throw exceptions:
new Uri("https://:80");
new Uri("https:///example.com");
new Uri("://example.com");
Uri class will verify that the Uri is a valid Uri. Whether a file exists or not at a given Uri is something that you will have to write code for. It wouldn't be covered by regex either. However if your question is to check whether the Uri is valid as per the specification when provided for a file, then the Uri class will handle that too.
For validating correct file extensions, you can check whether the URL ends with certain strings, such as ".png", ".jpg" using String.EndsWith.
Upvotes: 1