How to check if a URL is valid

后端 未结 9 1151
自闭症患者
自闭症患者 2020-11-28 04:23

How can I check if a string is a valid URL?

For example:

http://hello.it => yes
http:||bra.ziz, => no

If this is a valid URL

9条回答
  •  执念已碎
    2020-11-28 04:39

    For me, I use this regular expression:

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

    Option:

    • i - case insensitive
    • x - ignore whitespace in regex

    You can set this method to check URL validation:

    def valid_url?(url)
      return false if url.include?("

    To use it:

    valid_url?("http://stackoverflow.com/questions/1805761/check-if-url-is-valid-ruby")
    

    Testing with wrong URLs:

    • http://ruby3arabi - result is invalid
    • http://http://ruby3arabi.com - result is invalid
    • http:// - result is invalid
    • http://test.com\n
提交回复
热议问题