class WebSite < ActiveRecord::Base
validates_format_of :url, :with => /^((http|https):\/\/)*[a-z0-9_-]{1,}\.*[a-z0-9_-]{1,}\.[a-z]{2,4}\/*$/i
def validate
errors.add(:url, "unexistent") unless WebSite.existent_url?(:url)
end
def self.existent_url?(url)
uri = URI.parse(url)
http_conn = Net::HTTP.new(uri.host, uri.port)
resp, data = http_conn.head("/" , nil)
resp.code == "200"
end
end
Ruby on Rails: Validate URL 4
Posted by luca
on Wednesday, February 21
Hi, just a snippet to validate an url with Ruby on Rails.
Comments
-
What about .info domains? I think you should probably change the last part to [a-z]{2,4}\/*$/i
-
Yes, of course..
-
I get a exception with the above code, 'bad URI(is not URI?): url' why would that be? sorry if this is a stupid question.
-
Oh, this is an old snippet, I don't like it anymore. Anyway, your exception was probably raised by URI.parse(url), because your url is not well-formed. I guess ActiveRecord has invoked #validate first, so the format of your url wasn't checked by the proper code.
