问题描述
如果条目如下有效或无效,如何验证URL:
www.com - 应无效
http ://ww.try.net - 应该是无效的
http://winner.com - 应该是有效的
url = null =应该是无效的
以下是我制作的方法,不能验证上述情况。
提前感谢您的帮助
我尝试过:
How to validate URL if valid or invalid if the entry is like this:
www.com - should be invalid
http://ww.try.net - should be invalid
http://winner.com - should be valid
url = null = should be invalid
Below is the method I made which does not validate the above scenario.
Thank you in advance for your kind help
What I have tried:
<pre> public bool IsUrlValid(string webUrl)
{
if (webUrl == null) return false;
return Regex.IsMatch(webUrl, @"(http|https)://(([www\.])?|([\da-z-\.]+))\.([a-z\.]{2,3})$");
}
推荐答案
List<string> uris = new List<string>(){"www.com", "http://ww.try.net", "http://winner.com", "url = null"};
var result = uris.Select(x=> new {Uri = x, IsValid = Uri.IsWellFormedUriString(x, UriKind.Absolute)});
foreach(var u in result)
{
Console.WriteLine("'{0}' is{1}valid", u.Uri, u.IsValid ? " ":" NOT ");
}
结果:
Result:
'www.com' is NOT valid
'http://ww.try.net' is valid
'http://winner.com' is valid
'url = null' is NOT valid
如果你想使用Regex,你可以使用它: ^ http(s)?://([\w-] +。)+ [\w - ] +(/ [\\\-。/?%& =])?
In case, you want to use Regex instead, you can use this: ^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?
这篇关于如果在C#中输入的内容如此有效或无效,如何验证URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!