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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18568244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:57:50  来源:igfitidea点击:

URL Validation REGEX - URL just valid with http://

javascriptjqueryregexvalidationurl

提问by Peesen87

How it works

这个怎么运作

I have an input field to enter the URL of a Website and i wanna check it and if the URL is OK i will give the inputfield a class("validated_ok") and remove a class ("cf_required") and if its wrong the other way around.

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

Problem

问题

The url should just be right if it is written with http://but actually its also right with just www(www.google.ch). How i have to change the regex?

url 应该是正确的,如果它是用写的,http://但实际上它也是正确的www( www.google.ch)。我必须如何更改正则表达式?

Javascript

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");
    }
});

回答by Ant P

Remove the |www\.?

删除|www\.?

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

回答by DGS

just change your regex to make http(s) required

只需更改您的正则表达式即可使 http(s) 成为必需

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

回答by EdsonF

This will work:

这将起作用:

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

Hope it may help you

希望它可以帮助你

回答by Raphael

Shorter way:

更短的方法:

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

You can test it in this wonderful regex editor: https://regex101.com/

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

回答by Balgopal Prusty

^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