Javascript JS 正则表达式 url 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30970068/
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-23 06:00:30  来源:igfitidea点击:

JS Regex url validation

javascriptjqueryregexweb

提问by motis10

I tried to validate url with or without http No matter what i did the function return false. I checked my regex string in this site: http://regexr.com/And its seen as i expect.

我尝试使用或不使用 http 来验证 url 不管我做了什么,函数都返回 false。我在这个网站上检查了我的正则表达式字符串:http: //regexr.com/并且它和我期望的一样。

    function isUrlValid(userInput) {
        var regexQuery = "/(http(s)?://.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/";
        var url = new RegExp(regexQuery,"g");
        if (url.test(userInput)) {
            alert('Great, you entered an E-Mail-address');
            return true;
        }
        return false;
    }

I fix the problem by change the .test to .match and leave the regex as is.

我通过将 .test 更改为 .match 并保留正则表达式来解决问题。

回答by motis10

I change the function to Match + make a change here with the slashes and its work: (http(s)?://.)

我将函数更改为 Match + 在此处使用斜杠及其工作进行更改:(http(s)?://.)

The fixed function:

固定功能:

function isUrlValid(userInput) {
    var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
    if(res == null)
        return false;
    else
        return true;
}

回答by m69 ''snarky and unwelcoming''

I believe the other answer will reject some valid url's (like domain names in uppercase or long sub-domains) and allow some invalid ones (like http://www.-example-.comor www.%@&.com). I tried to take into account a number of additional url syntax rules (without getting into internationalisation).

我相信另一个答案会拒绝一些有效的 url(比如大写的域名或长子域)并允许一些无效的(比如http://www.-example-.com或 www.%@&.com)。我试图考虑一些额外的 url 语法规则(没有进入国际化)。

function isUrlValid(userInput) {
    var regexQuery = "^(https?://)?(www\.)?([-a-z0-9]{1,63}\.)*?[a-z0-9][-a-z0-9]{0,61}[a-z0-9]\.[a-z]{2,6}(/[-\w@\+\.~#\?&/=%]*)?$";
    var url = new RegExp(regexQuery,"i");
    return url.test(userInput);
}
var input = ["https://o.sub-domain.example.com/foo/bar?foo=bar&boo=far#a%20b",
             "HTTP://EX-AMPLE.COM",
             "example.c",
             "example-.com"];
for (var i in input) document.write(isUrlValid(input[i]) + ": " + input[i] + "<br>");

To also allow IP addresses and port numbers, the regex is:

为了还允许 IP 地址和端口号,正则表达式是:

"^(https?://)?(((www\.)?([-a-z0-9]{1,63}\.)*?[a-z0-9][-a-z??0-9]{0,61}[a-z0-9]\??.[a-z]{2,6})|((\d{1??,3}\.){3}\d{1,3}))??(:\d{2,4})?(/[-\w@??\+\.~#\?&/=%]*)?$??"  

To also allow query strings without a slash between the domain name and the question mark (which is theoretically not allowed, but works in most real-life situations), the regex is:

为了还允许在域名和问号之间没有斜线的查询字符串(理论上是不允许的,但在大多数现实生活中都有效),正则表达式是:

"^(https?://)?(((www\.)?([-a-z0-9]{1,63}\.)*?[a-z0-9][-a-z??0-9]{0,61}[a-z0-9]\??.[a??-z]{2,6})|((\d??{1,3}\.){3}\d{1,3}??))(:\d{2,4})?((/|\???)[-\w@\+\.~#\?&??/=%]*)?$"

To also make sure that every % is followed by a hex number, the regex is:

为了确保每个 % 后跟一个十六进制数,正则表达式是:

"^(https?://)?(((www\.)?([-a-z0-9]{1,63}\.)*?[a-z0-9][-a-z??0-9]{0,61}[a-z0-9]\??.[a-z]{2,6})|((\d{1??,3}\.){3}\d{1,3}))??(:\d{2,4})?((/|\?)??(((%[0-9a-f]{2})|[-\??\w@\+\.~#\?&/=])*??))?$"

(Note: as John Wu mentioned in a comment, there are valid single-letter domains).

(注意:正如 John Wu 在评论中提到的,存在有效的单字母域

回答by Rahul Mahadik

Try this code.

试试这个代码。

function CheckURL(fieldId, alertMessage) {
    var url = fieldId.value;
    if(url !== "")
    {
        if (url.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g) !== null)
            return true;
        else {
            alert(alertMessage);
            fieldId.focus();
            return false;
        }
    }
}

var website = document.getElementById('Website');
if (!CheckURL(website, "Enter a valid website address")) {
    return false;
}

回答by AmerllicA

Actually, this question needs a powerful regexand the following code is not very hard to understand, please see below(ES6):

其实这个问题需要一个强大的regex,下面的代码不是很难理解,请看下面(ES6):

const isValidUrl = urlString => {
  const urlRegex = /^((http(s?)?):\/\/)?([wW]{3}\.)?[a-zA-Z0-9\-.]+\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/g;
  const result = urlString.match(urlRegex);
  return result !== null;
};