0

I know there are other ways of checks and questions like this but still trying to debug my piece of code. It checks if user entered the url without "http://"

 //page is a global variable, a string in this case
 //loadPage(string url) loads the requested page;
 private void checkIfUrlRight(string s)
    {
        if (!s.StartsWith("http://"))
        {
            if (!s.Contains("www."))
            {
                s += "http://www.";
                page = s;
            }
            else
            {
                s += "http://";
                page = s;
            }
            urlRTextBox.Text = page;
            loadPage(page);
        }
        else
            page = s;
        urlRTextBox.Text = page;
        loadPage(page);

    }

I get an error when loading a page, it says that Url is wrong. Will actually my code make any sense or shall I just switch to complicated stuff like regex (looked through the web, looks harsh, don't where to start) or playing around with c# Uri class? Any suggestions?

Thanks in advance.

Messerschmitt
  • 75
  • 2
  • 7
  • 1
    possible duplicate of [Regular Expression for URL validation](http://stackoverflow.com/questions/9289007/regular-expression-for-url-validation) – Alastair Pitts Oct 30 '13 at 02:22

1 Answers1

2

There is a method in the Uri class that validates certain uri, you can use it as follows:

void checkIfUrlRight(string s)
{
  if (Uri.IsWellFormedUriString(s, UriKind.RelativeOrAbsolute))
  { 
    urlRTextBox.Text = page;
    loadPage(page);
  }
}

EDIT:

Note that actually not every URI is URL (described here). But I believe for your case (when all URLs are URIs) it is the simplest way to validate.

Community
  • 1
  • 1
heq
  • 412
  • 2
  • 8