I need a check that returns true for the following website urls: I need to make sure that websites that start as www. pass as true. Also google.com should return true.
www.google.com
google.com
http://google.com
http://www.google.com
https://google.com
https://www.google.com
I have been using IsWellFormedUriString
and haven't gotten anywhere. It keeps returning true. I also have used Uri.TryCreate
and can't get it to work either. There is so much on Stack Overflow regarding this topic but none of them are working. I must be doing something wrong.
Here is my ValidateUrl
function:
public static bool ValidateUrl(string url)
{
try
{
if (url.Substring(0, 3) != "www." && url.Substring(0, 4) != "http" && url.Substring(0, 5) != "https")
{
url = "http://" + url;
}
if (Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
{
Uri strUri = new Uri(url);
return true;
}
else
{
return false;
}
}
catch (Exception exc)
{
throw exc;
}
}
And I am calling it like this:
if (ValidateUrl(url) == false) {
validationErrors.Add(new Error()
{
fieldName = "url",
errorDescription = "Url is not in correct format."
});
}
It is returning true for htp:/google.com
. I know there's a lot on this site regarding this topic but I have been trying to get this to work all day yesterday and nothing is working.
I got it working by writing a small helper method that uses Regex to validate the url.
The following URL's pass:
google.com
www.google.com
It fails on:
www.google.com/a bad path with white space/
Below is the helper method I created:
public static bool ValidateUrl(string value, bool required, int minLength, int maxLength)
{
value = value.Trim();
if (required == false && value == "") return true;
if (required && value == "") return false;
Regex pattern = new Regex(@"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$");
Match match = pattern.Match(value);
if (match.Success == false) return false;
return true;
}
This allows users to input any valid url, plus it accounts for bad url paths with white space which is exactly what I needed.