How to validate url?

后端 未结 4 578
自闭症患者
自闭症患者 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: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;
        }
    

提交回复
热议问题