How to validate url?

后端 未结 4 572
自闭症患者
自闭症患者 2020-12-21 06:11

I want to validate urls. It should accept:

http://google.com

http://www.google.com

www.google.com

google.com

I refer Regex to match URL

相关标签:
4条回答
  • 2020-12-21 06:14
    function isUrl(s) {
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
        return regexp.test(s);
    }
    
    0 讨论(0)
  • 2020-12-21 06:22

    This is a better way I think should be used to validate urls

    reg = /https?:\/\/w{0,3}\w*?\.(\w*?\.)?\w{2,3}\S*|www\.(\w*?\.)?\w*?\.\w{2,3}\S*|(\w*?\.)?\w*?\.\w{2,3}[\/\?]\S*/
    reg.test('www.google.com')    # will return true
    reg.test('www.google')        # will return false
    

    Let me know if you still not getting it correct.

    0 讨论(0)
  • 2020-12-21 06:27

    This simple helper method uses Regex to validate URLs and will pass on each of your test cases. It also takes into account for whitespace so google.com/a white space/ will fail.

        public static bool ValidateUrl(string value, bool required, int minLength, int maxLength)
        {
            value = value.Trim();
            if (required == false && value == "") return true;
            if (required && value == "") return false;
    
            Regex pattern = new Regex(@"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$");
            Match match = pattern.Match(value);
            if (match.Success == false) return false;
            return true;
        }
    
    0 讨论(0)
  • 2020-12-21 06:31

    Simply prepend http:// if it's not there and then test.

    if (inputURL.substring(0,7) != 'http://' && inputURL.substring(0,8) != 'https://') {
        inputURL = 'http://' + inputURL;
    }
    

    No large libraries required or anything, just a few lines of code.

    0 讨论(0)
提交回复
热议问题