0

所以我有一个我正在做的 URL 验证,它非常轻松,或多或少只是引导用户确保他们输入接近 URL。

所以我有一个正则表达式可以在测试人员中做我想做的事情。(仅选择多行)例如:http ://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

但是,当我在代码中调用它时,它会给出不同的结果。

isURLValid: function (value) {
    var urlRegex = new RegExp("^((http|https|ftp)\://)*([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
    return urlRegex.test(value);
}

要求:必须支持 http、https、非 http、非 https、www 和非 www URL 方案

有效的

http://www.adamthings.com
https://www.adamthings.com
www.adamthings.com
adamthings.com

无效的

http://www.adamthings
https://www.adamthings
www.adamthings
亚当斯

结果在测试仪中工作,在代码中我得到以上所有内容都是有效的。为什么正则表达式的反应不同?

4

2 回答 2

1

在javascript中:("\.com" === ".com"我认为这不是你想要的。)
尝试/regex/而不是new RegExp("regex")创建一个正则表达式。

于 2012-10-22T16:04:38.193 回答
0

If you want to allow something like

adamthings.com

which has no leading http://, https://, ftp:// or www. part, then you would need to list all allowed TLDs, such as com, net, etc., to prevent input such as

john.doe

to be valid as well.

Then your regex pattern should look like

^(?:https?:\/\/|ftp:\/\/)?(?:www\.)?(?!www\.)(?:(?!-)[a-z\d-]*[a-z\d]\.)+(?:com|net)

which checks just domain part of the link.

If you want to go further and check trailing part or link, then you need to add

(?:\/[^\/\s]*)*$

to the first part of pattern, however this (part of regex pattern) does not validate the url.

» Test link «

于 2012-10-22T16:26:51.740 回答