2

I need a check that returns true for the following website urls: I need to make sure that websites that start as www. pass as true. Also google.com should return true.

www.google.com

google.com

http://google.com

http://www.google.com

https://google.com

https://www.google.com

I have been using IsWellFormedUriString and haven't gotten anywhere. It keeps returning true. I also have used Uri.TryCreate and can't get it to work either. There is so much on Stack Overflow regarding this topic but none of them are working. I must be doing something wrong.

Here is my ValidateUrl function:

   public static bool ValidateUrl(string url)
   {
       try
       {
           if (url.Substring(0, 3) != "www." && url.Substring(0, 4) != "http" && url.Substring(0, 5) != "https")
           {
               url = "http://" + url;
           }
           if (Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
           {
               Uri strUri = new Uri(url);
               return true;
           }
           else
           {
               return false;
           }
       }
       catch (Exception exc)
       {
           throw exc;
       }
   }

And I am calling it like this:

if (ValidateUrl(url) == false) { 
    validationErrors.Add(new Error() 
    { 
        fieldName = "url", 
        errorDescription = "Url is not in correct format." 
    }); 
}

It is returning true for htp:/google.com. I know there's a lot on this site regarding this topic but I have been trying to get this to work all day yesterday and nothing is working.

Andrew Reese
  • 854
  • 1
  • 11
  • 27
  • 1
    you can simplify your if : replace if(ValidateUrl(url) == false) by if(!ValidateUrl(url)). Also, did you try to debug it? Add a break point in your ValidateUrl method and see where it goes – taktak Jul 30 '19 at 12:53
  • 1
    Take a look at this quick online compiler https://dotnetfiddle.net/fRNrNb That url, according to this method is valid – andyb952 Jul 30 '19 at 12:56
  • Ok so if it's valid using this method then I am going about it the wrong way. I don't want users to be able to enter an invalid website url. I want them to be able to copy from DB and paste into their browser and it's a valid website url. – Andrew Reese Jul 30 '19 at 12:58
  • 1
    `htp:/google.com` will get converted to `http://htp:/google.com` by your code, which is (also) a valid URL. You could simplify your first `if` in `ValidateUrl` with `!url.StartsWith("www") && !url.StartsWith("http") && !url.StartsWith("https")`, but I don't think that logic is correct. – Heretic Monkey Jul 30 '19 at 13:14
  • @HereticMonkey it is just prepending "http://" so if a user puts enters "htp:/google.com" the result will be "http://htp/google.com". My logic is off for sure. But +1 for the simplification! – Andrew Reese Jul 30 '19 at 13:17
  • Do note that HTML 5 has the [`input type="url"`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url), which can do the validation for you (with the caveat of browser support, obviously). – Heretic Monkey Jul 30 '19 at 13:18
  • Possible duplicate of [How to check whether a string is a valid HTTP URL?](https://stackoverflow.com/questions/7578857/how-to-check-whether-a-string-is-a-valid-http-url) – Heretic Monkey Jul 30 '19 at 13:28
  • You could try the `UriTemplateMatch` class to verify the URL against a pattern. Not sure if it checks the protocol though – Syntax Error Jul 30 '19 at 13:32
  • I was able to get this working by creating a helper method using Regex. It works exactly how I want it. I posted the answer below. – Andrew Reese Aug 12 '19 at 16:12

4 Answers4

2

If you want your users to copy and paste from the db into the browser and enter a valid site, I think you should validate the url format and at the same time verify the existence of the url for example:

    Uri.IsWellFormedUriString("http://www.google.com", UriKind.Absolute);   

It will be true again how the URL is in the correct form.

    WebRequest request = WebRequest.Create("http://www.google.com");
    try
     {
       request.GetResponse();
     }
   catch (Exception ex)
    {
     throw ex;
   }

An exception will return, if it is not possible to get the answer from the url

Hi.

Sergio
  • 138
  • 7
  • +1 for your help. Unfortunately I still wasn't able to get this to work. I may have to find a regex function for validation. I appreciate your help! – Andrew Reese Aug 02 '19 at 12:31
  • I was able to get create a helper method using regex that passed on everything I needed it to and failed on what I needed it to. I posted the answer below. It's just a simple boolean function. – Andrew Reese Aug 12 '19 at 16:11
  • Uri.IsWellFormedUriString succeeds for 'wibble://blah', 'httttp://blah' etc. This is correct as they are valid URIs. They may not be valid URLs though. – tjmoore Feb 05 '21 at 13:58
2

If I understand your question correct then I would check it like that:

public static bool ValidateUrl(string url)
{
    if (url.StartsWith("https://www.") || url.StartsWith("http://www.") || url.StartsWith("https://google.com") || url.StartsWith("http://google.com"))
    {
        return true;
    }
    else
    {
        return false;
    }
}

Any domain name not google.com but with https://www. or http://www. returns true otherwise false.

KH S
  • 444
  • 1
  • 4
  • 8
  • +1 for the url.StartsWith. I appreciate your answer and can actually use that check. Unfortunately a URL such as http://google.com/ a lot of spaces/hey.com would still return true with this. – Andrew Reese Aug 02 '19 at 12:29
  • 1
    I would write a list of the URL's which come out wrong and look for similarities, differences and what is equal. If you would post a few I might be of better help. I probably would split up the if statement. Do more checking for the ones which have unexpected results.Then within that failing if statement I would remove https://google.com and http://google.com from the url string and then check with an if statement if I find what I am looking for and if not return false. I usually just work on getting the correct results and once I have achieved that I work on optimising my code. – KH S Aug 04 '19 at 09:16
  • I was able to get create a helper method using regex that passed on everything I needed it to and failed on what I needed it to. I posted the answer below. It's just a simple boolean function. – Andrew Reese Aug 12 '19 at 16:10
0

If you want to test if an HTTP(S) url is good or not, you should use this : (credit : stackoverflow.com/a/56116499/215552 )

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

So in your case :

public static boolean ValidateUrl(string url){
    Uri uriResult;
    return Uri.TryCreate(url, UriKind.Absolute, out uriResult) 
        && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
}

// EDIT : try this :

public static bool ValidateUrl(string URL)
{
    string Pattern = @"(http(s)?://)?([\w-]+\.)+[\w-]+[\w-]+[\.]+[\][a-z.]{2,3}$+([./?%&=]*)?";
    Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    return Rgx.IsMatch(URL);
}
taktak
  • 90
  • 10
  • 1
    Please try my next solution. I use regex – taktak Jul 30 '19 at 13:18
  • This solution fails for "www.google,com/ a bear's nest". In other words it's not taking into account for whitespace. Also, failed on just "google.com". Definitley closer though! – Andrew Reese Jul 30 '19 at 13:24
  • 1
    If you're going to copy answers from another question, please at least give credit to those you're copying from. Your latest edit is a direct copy from https://stackoverflow.com/a/56116499/215552 – Heretic Monkey Jul 30 '19 at 13:29
  • @Heretic Monkey Done – taktak Jul 30 '19 at 13:32
0

I got it working by writing a small helper method that uses Regex to validate the url.

The following URL's pass:

google.com

www.google.com

http://google.com

http://www.google.com

https://google.com/test/test

https://www.google.com/test

It fails on:

www.google.com/a bad path with white space/

Below is the helper method I created:

    public static bool ValidateUrl(string value, bool required, int minLength, int maxLength)
    {
        value = value.Trim();
        if (required == false && value == "") return true;
        if (required && value == "") return false;

        Regex pattern = new Regex(@"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$");
        Match match = pattern.Match(value);
        if (match.Success == false) return false;
        return true;
    }

This allows users to input any valid url, plus it accounts for bad url paths with white space which is exactly what I needed.

Andrew Reese
  • 854
  • 1
  • 11
  • 27