How to check if a URL is valid

后端 未结 9 1167
自闭症患者
自闭症患者 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:44

    I prefer the Addressable gem. I have found that it handles URLs more intelligently.

    require 'addressable/uri'
    
    SCHEMES = %w(http https)
    
    def valid_url?(url)
      parsed = Addressable::URI.parse(url) or return false
      SCHEMES.include?(parsed.scheme)
    rescue Addressable::URI::InvalidURIError
      false
    end
    

提交回复
热议问题