Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a string is a valid HTTP URL?

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?

like image 532
Louis Rhys Avatar asked Sep 28 '11 05:09

Louis Rhys


People also ask

How do I check if a string is URL?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

What is a valid HTTP URL?

A URL is a valid URL if at least one of the following conditions holds: The URL is a valid URI reference [RFC3986]. The URL is a valid IRI reference and it has no query component. [RFC3987] The URL is a valid IRI reference and its query component contains no unescaped non-ASCII characters.

How do you validate a URL?

When you create a URL input with the proper type value, url , you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mis-types their web site's address, or provides an invalid one.

How do you check if a string is a valid URL in Java?

Using java.net.url url class to validate a URL. The idea is to create a URL object from the specified String representation. If we do not get exception while creating the object, we return true. Else we return false.


2 Answers

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); 
like image 190
Arabela Paslaru Avatar answered Oct 04 '22 08:10

Arabela Paslaru


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

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

MSDN: IsWellFormedUriString

like image 35
Kishath Avatar answered Oct 04 '22 09:10

Kishath