繁体   English   中英

URL验证REGEX - URL仅对http://有效

[英]URL Validation REGEX - URL just valid with http://

这个怎么运作

我有一个输入字段来输入网站的URL,我想检查它,如果URL正常,我将给输入字段一个类(“validated_ok”)并删除一个类(“cf_required”),如果它错了,另一个四处走走。

问题

如果它是用http://写的,那么网址应该是正确的,但实际上它也只是用wwwwww.google.ch )编写的。 我怎么改变正则表达式?

使用Javascript

// CHECK WEBSITE
$(".cf_required[name='website']").focusout(function() {
    var myVariable = $(this).val();
    if(/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(myVariable)){
        $(this).addClass("validated_ok").removeClass("cf_required")
    } else {
        $(this).removeClass("validated_ok").addClass("cf_required");
    }
});

删除|www\\.

^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$

只需更改你的正则表达式,使http(s)成为必需

/^http(s)?:\/\/(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test('www.google.com')

这将有效:

(?<Protocol>\w+):\/\/(?<Domain>[\w@][\w.:@]+)\/?[\w\.?=%&=\-@/$,]*

希望它可以帮到你

更短的方式:

(\w*\W*)?\w*(\.(\w)+)+(\W\d+)?(\/\w*(\W*\w)*)*

您可以在这个精彩的正则表达式编辑器中测试它: https//regex101.com/

^http(s?):\/\/(www\.)?(((\w+(([\.\-]{1}([a-z]{2,})+)+)(\/[a-zA-Z0-9\_\=\?\&\.\#\-\W]*)*$)|(\w+((\.([a-z]{2,})+)+)(\:[0-9]{1,5}(\/[a-zA-Z0-9\_\=\?\&\.\#\-\W]*)*$)))|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(([0-9]|([1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]+)+)(\/[a-zA-Z0-9\_\=\?\&\.\#\-\W]*)*)((\:[0-9]{1,5}(\/[a-zA-Z0-9\_\=\?\&\.\#\-\W]*)*$)*))$
In this http is mandatory and it can take port and sub resources also.
e.g http://example.com
    https://example.qwerty.com/id
    https://example.com:8989
    http://example.qwerty.com:8989/id
    https://10.1.1.1/id
    https://10.1.1.1:9090/id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM