JS Regex url validation

后端 未结 4 533
梦毁少年i
梦毁少年i 2021-02-07 12:41

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.

4条回答
  •  醉话见心
    2021-02-07 13:01

    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-.com or www.%@&.com). I tried to take into account a number of additional url syntax rules (without getting into internationalisation).

    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] + "
    ");

    To also allow IP addresses and port numbers, 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 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).

提交回复
热议问题