Search code examples
ruby-on-railsrubyregex

Check if given string is an URL


In my rails application I need to verify if the URL given by a user is really an URL. I'm only concerned with the HTTP protocol (and perhaps HTTPS, I have not looked into that at all), which leads me to believe that there might something already in rails that can do this work for me.

If not: can you recommend a regex string that does this? I've found some after googling but they all seem to have a problem or two according to user comments.

Thanks


Solution

  • Use the URI library.

    def uri?(string)
      uri = URI.parse(string)
      %w( http https ).include?(uri.scheme)
    rescue URI::BadURIError, URI::InvalidURIError
      false
    end
    

    This is a very simple example. The advantage of using the URI library over a regular expression is that you can perform complex checks.