【发布时间】:2011-03-08 15:41:13
【问题描述】:
您好,我需要验证一个文本框应该只接受 url 名称。 谁能告诉我。 我会很感激的。
【问题讨论】:
-
您可以使用正则表达式 - RegEx。它在验证模式中的字符串方面非常强大。
标签: c# winforms validation url textbox
您好,我需要验证一个文本框应该只接受 url 名称。 谁能告诉我。 我会很感激的。
【问题讨论】:
标签: c# winforms validation url textbox
我认为没有内置方法或类可用于验证字符串是否为合法 url。但是您可以使用正则表达式,例如 ["^a-zA-Z0-9-._"]+.([a-zA-Z][a-zA-Z]) 如果您使用 Ranhiru 的代码,您将无法正确使用例如 bild.de 和 s.int,它们都是有效的 url。
【讨论】:
您需要 URL 有效还是格式正确?如果是后者,那么您可能需要一个正则表达式,正如其他答案所指出的那样 - 但让它适用于 all URL 可能会很棘手。
如果是前者,那么只需尝试解析 URL。有几种方法可以做到这一点,每种方法都有缺点。例如,如果您使用“ping”,则需要事先删除任何前导“http://”。
但是,此方法并非万无一失,因为 a) 您可能没有互联网连接,并且 b) 主机可能已关闭。
【讨论】:
这个怎么样:
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 部分。
【讨论】:
您可以使用正则表达式来检查输入的文本是否是有效的 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
【讨论】:
简单得多:
/// <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;
}
【讨论】:
它对我有用
private bool ValidateURL(string urlText) { 布尔结果;
try
{
Uri check = new Uri(urlText);
result = true;
}
catch (UriFormatException)
{
result = false;
}
return result;
}
【讨论】: