简体   繁体   English

Windows窗体文本框应仅接受网址名称

[英]Windows forms text box should accept only url name

Hi I need to validate that a textbox should accept only url names. 嗨,我需要验证文本框应该只接受网址名称。 Can anybody tell me please. 请有人告诉我。 I would be really thankful. 我真的很感激。

I don´t think there is a built in method or class that you can use to validate a string as a legal url. 我不认为有一个内置的方法或类可以用来验证字符串作为合法的URL。 But you can use regex, something like ["^a-zA-Z0-9-._"]+.([a-zA-Z][a-zA-Z]) If you use the code from Ranhiru you will not get it right with for instance bild.de and s.int which are both valid urls. 但你可以使用正则表达式,类似[“^ a-zA-Z0-9 -._”] +。([a-zA-Z] [a-zA-Z])如果你使用Ranhiru的代码,你会不能用例如bild.de和s.int这两个都是有效的网址。

Do you need the URL to be valid or just of the right format? 您是否需要URL有效或只是正确的格式? If it's the latter then you will probably need a regex as other answers point out - but getting it to work for all URLs could be tricky. 如果它是后者那么你可能需要一个正则表达式,因为其他答案指出 - 但让它适用于所有 URL可能是棘手的。

If it's the former then simply try and resolve the URL. 如果是前者,那么只需尝试解析URL。 There are several ways of doing this, each has drawbacks. 有几种方法可以做到这一点,每种方法都有缺点。 For example, if you use "ping" then you'll need to remove any leading "http://" before hand. 例如,如果您使用“ping”,那么您需要事先删除任何前导“http://”。

However, this method isn't foolproof as a) you might not have an internet connection and b) the host might be down. 但是,这种方法并非万无一失,因为a)您可能没有互联网连接,而b)主机可能已关闭。

How about this: 这个怎么样:

    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;
        }
    }

If you only need to check that it's in the right format you can take out the UrlExists part. 如果您只需要检查它是否格式正确,您可以取出UrlExists部分。

Much simpler: 更简单:

    /// <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;
    }

its working for me 它为我工作

private bool ValidateURL(string urlText) { bool result; private bool ValidateURL(string urlText){bool result;

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

    return result;
}

You can use Regular Expressions to check whether the entered text is a valid URL :) 您可以使用正则表达式来检查输入的文本是否是有效的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;

            }




        }

You can use this function as 您可以使用此功能

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

Check for more RegularExpressions of URL's in Here http://www.regexlib.com/Search.aspx?k=url&c=-1&m=5&ps=20 http://www.regexlib.com/Search.aspx?k=url&c=-1&m=5&ps=20中查看更多网址的RegularExpressions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM