How to check if a URL is valid

ruby

Solution

Notice:

As pointed by @CGuess, there's a bug with this issue and it's been documented for over 9 years now that validation is not the purpose of this regular expression (see https://bugs.ruby-lang.org/issues/6520).

Use the `URI` module distributed with Ruby:

require 'uri'

if url =~ URI::regexp
    # Correct URL
end

Like Alexander Günther said in the comments, it checks if a string contains a URL.

To check if the string is a URL, use:

url =~ /\A#{URI::regexp}\z/

If you only want to check for web URLs (`http` or `https`), use this:

url =~ /\A#{URI::regexp(['http', 'https'])}\z/

Problem

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 how can I check if this is relative to a image file?

Original source

Related problems