best URL validation

Your CheckURLValid is returning exactly what you have told it to.

To return True on all 4 URLs here are the issues


This is a relative url and you have specified UriKind.Absolute which means this is false.


This is an httpS (Secure) url and your method says

&& uriResult.Scheme == Uri.UriSchemeHttp;

which will limit you to only http addresses (NON secure)

To get the results you are wanting you will need to use the following method:

public static bool CheckURLValid(string strURL)
    Uri uriResult;
    return Uri.TryCreate(strURL, UriKind.RelativeOrAbsolute, out uriResult);

An alternative is to just use

Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute);

and not re implement functionality that all ready exists. If you wanted to wrap it it your own CheckUrlValid I would use the following:

public static bool CheckURLValid(string strURL)
    return Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute); ;

The main problem is that most strings are valid relative URL's so I would avoid using UriKind.RelativeOrAbsolute as is an invalid url. Most web browsers silently add HTTP:// to the string to make it a valid url. HTTP:// is a valid url.

Not sure if I'm missing something here, but just so others don't waste their time with Uri.IsWellFormedUriString, note that the following test fails:

public void TestURLValidation()
    bool result = Uri.IsWellFormedUriString("bad", UriKind.RelativeOrAbsolute);

I.e., the prescribed answer will consider "bad" as a valid address. I believe that's not the behavior most users are after.