tags:

views:

227

answers:

2

How can i check if a variable is a valid url? e.g.

http://hello.it ok http:||bra.ziz, no

and if this is a valid url how can i check if this is relative to a image file?

thanks

+4  A: 

Use the URI module distributed with Ruby:

require 'uri'

unless (url =~ URI::regexp).nil?
    # Correct URL
end
Mikael S
A: 

You could also use a regex, maybe something like http://www.geekzilla.co.uk/View2D3B0109-C1B2-4B4E-BFFD-E8088CBC85FD.htm assuming this regex is correct (I haven't fully checked it) the following will show the validity of the url.

url_regex = Regexp.new("((https?|ftp|file):((//)|(\\\\))+[\w\d:\#@%/;$()~_?\+-=\\\\.&]*)")

urls = [
    "http://hello.it",
    "http:||bra.ziz"
]

urls.each { |url|
    if url =~ url_regex then
        puts "%s is valid" % url
    else
        puts "%s not valid" % url
    end
}

The above example outputs:

http://hello.it is valid
http:||bra.ziz not valid
Jamie