By Louis Rhys


2011-09-28 05:48:08 8 Comments

There are the Uri.IsWellFormedUriString and Uri.TryCreate methods, but they seem to return true for file paths etc.

How do I check whether a string is a valid (not necessarily active) HTTP URL for input validation purposes?

9 comments

@Marco Concas 2019-05-13 16:34:30

Try that:

bool IsValidURL(string URL)
{
    string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
    Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    return Rgx.IsMatch(URL);
}

It will accept URL like that:

  • http(s)://www.example.com
  • http(s)://stackoverflow.example.com
  • http(s)://www.example.com/page
  • http(s)://www.example.com/page?id=1&product=2
  • http(s)://www.example.com/page#start
  • http(s)://www.example.com:8080
  • http(s)://127.0.0.1
  • 127.0.0.1
  • www.example.com
  • example.com

@Ifeanyi Chukwu 2019-04-12 20:47:15

bool passed = Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)

@Harsha Biyani 2019-04-13 05:36:46

Your answer came in lower quality posts. Please provide some explanation even though your code is self explanatory.

@Ahmed Abdelhameed 2018-10-12 05:37:54

All the answers here either allow URLs with other schemes (e.g., file://, ftp://) or reject human-readable URLs that don't start with http:// or https:// (e.g., www.google.com) which is not good when dealing with user inputs.

Here's how I do it:

public static bool ValidHttpURL(string s, out Uri resultURI)
{
    if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase))
        s = "http://" + s;

    if (Uri.TryCreate(s, UriKind.Absolute, out resultURI))
        return (resultURI.Scheme == Uri.UriSchemeHttp || 
                resultURI.Scheme == Uri.UriSchemeHttps);

    return false;
}

Usage:

string[] inputs = new[] {
                          "https://www.google.com",
                          "http://www.google.com",
                          "www.google.com",
                          "google.com",
                          "javascript:alert('Hack me!')"
                        };
foreach (string s in inputs)
{
    Uri uriResult;
    bool result = ValidHttpURL(s, out uriResult);
    Console.WriteLine(result + "\t" + uriResult?.AbsoluteUri);
}

Output:

True    https://www.google.com/
True    http://www.google.com/
True    http://www.google.com/
True    http://google.com/
False

@Epirocks 2019-03-18 17:59:43

This lets through single words like "mooooooooo" but used in conjunction with Uri.IsWellFormedUriString could be good

@Ahmed Abdelhameed 2019-03-19 09:40:20

@Epirocks That's a good point. The problem is that http://mooooooooo is, in fact, a valid Uri. Therefore, you can't check for Uri.IsWellFormedUriString after inserting "http://" and if you check for it before, anything that doesn't have a Scheme will be rejected. Maybe what can be done is we check for s.Contains('.') instead.

@Epirocks 2019-03-19 11:02:11

moooooo by itself doesn't look like a url as it has no protocol on it. What I did was take out your regex match call, and &&'ed it with IsWellFormedUriString as well.

@Ahmed Abdelhameed 2019-03-19 11:05:54

@Epirocks Exactly! The problem is that if you use IsWellFormedUriString before adding the http://, you'll end up rejecting things like google.com and if you use it after adding the http://, it'll still return true for http://mooooooooo. That's why I suggested checking if the string contains a . instead.

@Epirocks 2019-03-20 16:14:52

that's fine for me anyway I don't want to accept a url without http or https on it. So I use IsWellFormedUriString first, then use your function without regex. bool bResult = (Uri.IsWellFormedUriString(s, UriKind.Absolute) && ValidHttpURL(s, out uriResult)); Thanks

@Erçin Dedeoğlu 2014-11-02 14:12:36

    public static bool CheckURLValid(this string source)
    {
        Uri uriResult;
        return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
    }

Usage:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

UPDATE: (single line of code) Thanks @GoClimbColorado

public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps;

Usage:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

@Zauber Paracelsus 2016-02-11 17:35:07

This does not appear to handle www urls. IE: www.google.com is shown as invalid.

@Erçin Dedeoğlu 2016-02-12 06:56:59

@ZauberParacelsus "www.google.com" is invalid. URL mean should start with "http","ftp","file" etc. string should be "http:// www.google.com" without space

@GoClimbColorado 2018-05-24 16:38:54

Today, the out parameter can make an improvement Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps

@Erçin Dedeoğlu 2018-05-25 07:41:08

Updated the code, thanks. @GoClimbColorado

@Kishath 2016-05-05 12:56:55

This method works fine both in http and https. Just one line :)

if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))

MSDN: IsWellFormedUriString

@Squiggle 2017-06-12 09:43:24

This will return true for non-HTTP URIs (i.e. any other scheme such as file:// or ldap://. This solution should be coupled with a check against the scheme - e.g. if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) ...

@whitneyland 2017-10-21 20:09:13

Fails 17 tests here: dotnetfiddle.net/XduN3A

@Marcus 2018-03-28 09:08:17

Is this RFC3986 compliant?

@X Stylish 2018-11-27 14:54:36

@Squiggle That's exactly what I want it to check, everything since I'm making a Downloader. So, this answer is the best method for me.

@Arabela Paslaru 2011-09-28 10:30:34

Try this to validate HTTP URLs (uriName is the URI you want to test):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;

Or, if you want to accept both HTTP and HTTPS URLs as valid (per J0e3gan's comment):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

@user1017882 2013-01-02 10:58:06

Should this read uriResult.Scheme instead of uriName.Scheme? I'm using the overload to TryCreate that takes String instead of Uri as it's first parameter.

@Fiarr 2014-01-22 19:04:10

You may want to add more conditions to the uriResult.Scheme == ... Specifically https. It depends on what you need this for, but this small change was all I needed for it to work perfectly for me.

@J0e3gan 2014-11-02 09:40:13

To be clear per @Fiarr's comment, the "small change" needed to account for HTTPS in addition to HTTP URLs is: bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps;

@Rob Sedgwick 2015-10-06 15:34:52

Here's an extension method for a string which does all the above: public static bool IsUrl(this string str) { Uri uriResult; bool result = Uri.TryCreate(str, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); return result; }

@mtkachenko 2016-02-05 08:21:23

What if url contains hashbang?

@barlop 2016-08-02 13:12:27

jon schneider has incorporated j0e3gan's comment into the answer posted here.

@Kailash P 2016-09-22 13:49:25

this way fails for URL like abcde. It says this is a valid URL.

@navigator_ 2016-10-20 16:36:55

@KailashP a URL in that format could indeed be valid, for example on my company's intranet devinfo takes me to a sharepoint page

@Jonathan Wood 2016-11-26 00:34:56

If the URL is deemed to be a relative URL, accessing uriResult.Scheme will throw an exception.

@raveturned 2017-01-27 13:55:23

@JonathanWood In this case if a relative URL is passed in for 'uriName', 'Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)' will return false and 'uriResult.Scheme' will not be accessed, so no exception will be thrown.

@RNobel 2017-03-17 14:47:57

What's the advantage over using Uri.IsWellFormedUriString, which is shorter?

@Richard 2017-06-08 10:14:29

Or in .NET Core, C#7 (where the constants in the Uri class are gone...): bool result = Uri.TryCreate(uriName, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == "http" || uriResult.Scheme == "https");

@Ian Grainger 2017-07-21 11:21:10

@KailashP is right - I don't think I like this code without an extra check: && uriResult != null!

@whitneyland 2017-10-21 20:04:01

Looks like this technique fails 22 out of 75 tests dotnetfiddle.net/XduN3A

@Radu 2018-02-21 08:44:58

@Lee what is the better option to test the url?

@Marcus 2018-03-28 08:51:05

Does this mean - Url complies with RFC3986 ?

@Sagar Panwala 2019-09-16 10:44:57

@whitneyland : Do you have any solution for this please ?

@Eranda 2014-09-03 04:15:12

Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
    return false;
else
    return true;

Here url is the string you have to test.

@JSON 2018-08-16 16:12:25

null == url check is horribly reduntant

@Miserable Variable 2011-09-28 06:14:33

After Uri.TryCreate you can check Uri.Scheme to see if it HTTP(s).

@user3760031 2014-06-20 12:02:17

This would return bool:

Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)

@Isantipov 2014-06-20 12:23:44

I think the OP specifically mentioned, he doesn't like Uri.IsWellFormedUriString as it gives true for file paths. Do you have a solution for this problem?

Related Questions

Sponsored Content

39 Answered Questions

18 Answered Questions

[SOLVED] How do I modify the URL without reloading the page?

73 Answered Questions

31 Answered Questions

[SOLVED] (Built-in) way in JavaScript to check if a string is a valid number

73 Answered Questions

[SOLVED] How can I get query string values in JavaScript?

15 Answered Questions

[SOLVED] How to change the URI (URL) for a remote Git repository?

  • 2010-03-12 12:48:47
  • e-satis
  • 1346760 View
  • 3377 Score
  • 15 Answer
  • Tags:   git url git-remote

84 Answered Questions

[SOLVED] How to validate an email address in JavaScript

52 Answered Questions

[SOLVED] What is the best regular expression to check if a string is a valid URL?

8 Answered Questions

[SOLVED] How are parameters sent in an HTTP POST request?

4 Answered Questions

[SOLVED] How to check that a uri string is valid

  • 2011-01-29 05:04:26
  • Manuel
  • 79153 View
  • 60 Score
  • 4 Answer
  • Tags:   c# .net uri

Sponsored Content