【问题标题】:Windows forms text box should accept only url nameWindows 窗体文本框应仅接受 url 名称
【发布时间】:2011-03-08 15:41:13
【问题描述】:

您好,我需要验证一个文本框应该只接受 url 名称。 谁能告诉我。 我会很感激的。

【问题讨论】:

  • 您可以使用正则表达式 - RegEx。它在验证模式中的字符串方面非常强大。

标签: c# winforms validation url textbox


【解决方案1】:

我认为没有内置方法或类可用于验证字符串是否为合法 url。但是您可以使用正则表达式,例如 ["^a-zA-Z0-9-._"]+.([a-zA-Z][a-zA-Z]) 如果您使用 Ranhiru 的代码,您将无法正确使用例如 bild.de 和 s.int,它们都是有效的 url。

【讨论】:

  • 是的,我同意我的正则表达式不适用于所有情况。但是使用不同的正则表达式对他有用:)
【解决方案2】:

您需要 URL 有效还是格式正确?如果是后者,那么您可能需要一个正则表达式,正如其他答案所指出的那样 - 但让它适用于 all URL 可能会很棘手。

如果是前者,那么只需尝试解析 URL。有几种方法可以做到这一点,每种方法都有缺点。例如,如果您使用“ping”,则需要事先删除任何前导“http://”。

但是,此方法并非万无一失,因为 a) 您可能没有互联网连接,并且 b) 主机可能已关闭。

【讨论】:

    【解决方案3】:

    这个怎么样:

        public void Test()
        {
            Uri result = UrlIsValid("www.google.com");
            if (result == null)
            {
                //Invalid Url format
            }
            else
            {
                if (UrlExists(result))
                {
                    //Url is valid and exists
                }
                else
                {
                    //Url is valid but the site doesn't exist
                }
            }
            Console.ReadLine();
        }
    
        private static Uri UrlIsValid(string testUrl)
        {
            try
            {
                if (!(testUrl.StartsWith(@"http://") || testUrl.StartsWith(@"http://")))
                {
                    testUrl = @"http://" + testUrl;
                }
                return new Uri(testUrl);
            }
            catch (UriFormatException)
            {
                return null;
            }   
        }
    
        private static bool UrlExists(Uri validUri)
        {
            try
            {   
                WebRequest.Create(validUri).GetResponse();
                return true;
            }
    
            catch (WebException)
            {
                return false;
            }
        }
    

    如果您只需要检查它的格式是否正确,您可以取出 UrlExists 部分。

    【讨论】:

      【解决方案4】:

      您可以使用正则表达式来检查输入的文本是否是有效的 URL :)

      using System.Text.RegularExpressions;
      
      private bool validateURL()
              {
      
                  Regex urlCheck = new Regex("^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$");
      
                  if (urlCheck.IsMatch(txtUrlAddress.Text))
                      return true;
                  else
                  {
                      MessageBox.Show("The url address you have entered is incorrect!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
                      return false;
      
                  }
      
      
      
      
              }
      

      你可以把这个函数当作

         if (validateURL() == true)
                //Do something
          else
                //Do something else
      

      在这里查看更多 URL 的正则表达式 http://www.regexlib.com/Search.aspx?k=url&c=-1&m=5&ps=20

      【讨论】:

      • 首先 com、org、net、mil 和 edu 不是唯一有效的域名结尾,而且 OP 也没有说它必须是您的域名的严格根正则表达式需要。
      • @Davy8,这只是一个建议的解决方案。他可以检查并查看是否有任何其他他认为最好的正则表达式并使用它。而且我看不到任何其他方式可以逐个字符地检查它是否是有效的 url :)
      【解决方案5】:

      简单得多:

          /// <summary>
          /// Validates that the URL text can be parsed.
          /// </summary>
          /// <remarks>
          /// Does not validate that it actually points to anything useful.
          /// </remarks>
          /// <param name="urlText">The URL text.</param>
          /// <returns></returns>
          private bool ValidateURL(string urlText)
          {
              bool result;
      
              try
              {
                  Uri check = new Uri(urlText);
                  result = true;
              }
              catch (UriFormatException)
              {
                  result = false;
              }
      
              return result;
          }
      

      【讨论】:

        【解决方案6】:

        它对我有用

        private bool ValidateURL(string urlText) { 布尔结果;

            try
            {
                Uri check = new Uri(urlText);
                result = true;
            }
            catch (UriFormatException)
            {
                result = false;
            }
        
            return result;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-03-01
          • 2021-01-30
          • 2016-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多