网址验证的正则表达式

Regular expression for Website address validation

我有一个用户输入来提供网站地址,显然大多数用户不知道什么是正确格式 url 所以我寻找一个将遵循此规则的正则表达式的网站地址:

1) www.someaddress.com - 正确
2) someaddress.com -
3) http://someaddress.com -
4) https://someaddress.com -
5) https://www.someaddress.co.il -
6) http://www.someaddress.com -

我使用这个 正则表达式:

[RegularExpression(@"^((http|ftp|https|www)://)?([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#$\%\^\&\*\(\)_\-\=\+\\/\?\.\:\;\'\,]*)?$", ErrorMessage = "Not a valid website address")]
public string SiteUrl { get; set; }

但它没有用,因为它几乎允许每个字符串通过。

请提供数据注释答案,而不是以下答案:

Uri.IsWellFormedUriString

因为 .net 不支持自定义属性的客户端验证。

有一个 UrlAttribute 来验证 URL,但它确实强制执行协议,这似乎是您不想要的。

但是,源代码是可用的,use a regular expression您可以窃取和修改它。仅将协议部分修改为您想要的可选方式,您会得到:

^((http|ftp|https)://)?(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$

(旁注:我注意到你的正则表达式允许 www://,这很可疑。我把它拿出来了,但如果你确实需要它,那么你可以添加它。)

这些是我测试的值:

www.someaddress.com             Yes
someaddress.com                 Yes
http://someaddress.com          Yes
https://someaddress.com         Yes
https://www.someaddress.co.il   Yes
cow                             No
hi hello.com                    No
this/that.com                   No

comments of the source code 中确实说:

This attribute provides server-side url validation equivalent to jquery validate, and therefore shares the same regular expression. See unit tests for examples.