Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Uri from String

I need an Uri validation method. So, strings like:

"http://www.google.com", "www.google.com", "google.com"

..must be validated as Uri's. And also normal strings like "google" must not be validated as Uri's. To do this checking, I use two methods: UriBuilder and Uri.TryCreate().

The problem with UriBuilder is that any string I give it, it returns an Uri out of it. When I pass a normal string in its constructor, it gives it a scheme and returns "http://google/" which is not the behavior I want.

The problem with Uri.TryCreate() is that, while it works ok with "http://www.google.com" and "www.google.com", when I give it "google.com" it does not validate is as an Uri.

I thought about doing checks on the string, if it starts with http:// or www, send the string to the UriBuilder class, but this does not help with "google.com" which also must be an Uri.

How can I validate stuff like "google.com" as an Uri, but not "google"? Checking the end of the string for .com, .net , .org doesn't seem flexible.

like image 603
Amc_rtty Avatar asked Sep 09 '10 06:09

Amc_rtty


People also ask

How do I check if my URI is valid?

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.

How do you check if a string is a URL in C#?

Use the StartWith() method in C# to check for URL in a String.

What is URI string in C#?

Uri(String, UriKind) Initializes a new instance of the Uri class with the specified URI. This constructor allows you to specify if the URI string is a relative URI, absolute URI, or is indeterminate. public: Uri(System::String ^ uriString, UriKind uriKind); C# Copy.

Is URI a string?

A URI is a string containing characters that identify a physical or logical resource. URI follows syntax rules to ensure uniformity. Moreover, it also maintains extensibility via a hierarchical naming scheme. The full form of URI is Uniform Resource Identifier.


1 Answers

public static bool IsValidUri(string uriString)
{
    Uri uri;
    if (!uriString.Contains("://")) uriString = "http://" + uriString;
    if (Uri.TryCreate(uriString, UriKind.RelativeOrAbsolute, out uri))
    {
        if (Dns.GetHostAddresses(uri.DnsSafeHost).Length > 0)
        {
            return true;
        }
    }
    return false;
}
like image 152
tidwall Avatar answered Oct 05 '22 21:10

tidwall