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.
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.
Use the StartWith() method in C# to check for URL in a String.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With