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.
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
Comments

Leave a response

  1. saschaDecember 16, 2007 @ 04:45 PM
    What about .info domains? I think you should probably change the last part to [a-z]{2,4}\/*$/i
  2. l.guidiDecember 16, 2007 @ 04:45 PM
    Yes, of course..
  3. LeonSeptember 15, 2008 @ 05:20 PM
    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.
  4. Luca GuidiSeptember 16, 2008 @ 09:25 AM
    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.
Comment