带或不带http和www的URL验证

时间:2014-08-27 15:46:33

标签: javascript asp.net regex validation

所有正则表达式都传递给js fiddle

当我将此正则表达式移动到我的asp.net页面时,正则表达式验证器,#3rd,#sever和#eight被视为无效。

ASP.net:

<asp:RegularExpressionValidator ID="RegularExpressionValidator8" ControlToValidate="txtHomePage"
                                                    runat="server" CssClass="StandardText" Display="Dynamic" SetFocusOnError="true"
                                                    ErrorMessage="Invalid URL" ValidationExpression="^(?!www | www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$"></asp:RegularExpressionValidator>

JavaScript代码:

function checkUrlTest(url){

    //   /^(?:(http|https|ftp):\/\/)?(?:[\w-]+\.)+[a-z]{2,6}(\/)?/i
    //  ^(?!www | www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$

    var urlregex = new RegExp("^(?!www | www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$")

            return urlregex.test(url);
        }
var one = "yahoo.com";
var two = "www.yahoo.com";
var three = "http://www.yahoo.com";  //fails on .net page
var four = "yahoo.org";
var five = "somesite.org"
var six = "www.somesite.org"
var seven = "http://somesite.org"    //fails on .net page
var eight = "https://www.somesite.org"   //fails on .net page
var nine = "somesite.org?case=1"

        alert(
            one + '===> ' + checkUrlTest(one) + "\n" +
            two + '===> ' + checkUrlTest(two) + "\n" +
            three + '===> ' + checkUrlTest(three) + "\n" +
            four + '===> ' + checkUrlTest(four) + "\n" +
            five + '===> ' + checkUrlTest(five) + "\n" +
            six + '===> ' + checkUrlTest(six) + "\n" +
            seven + '===> ' + checkUrlTest(seven) + "\n" +
            eight + '===> ' + checkUrlTest(eight) + "\n" +
            nine + '===> ' + checkUrlTest(nine)
        );

这里缺少哪些我无法找到的?

1 个答案:

答案 0 :(得分:1)

^中的^(www | www\.)锚点会排除前面包含https?的行。您可以使用非捕获组和?来选择查找这些情况:

^(?:https?://|s?ftps?://)?(?!www | www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$

这将匹配除最后两行之外的所有行:

yahoo.com
www.yahoo.com
http://www.yahoo.com
yahoo.org
somesite.org
www.somesite.org
http://somesite.org
https://www.somesite.org
somesite.org?case=1

www somesite.org   // Space after 'www'
 www.example.com   // Leading space

regex101 example