Quick and Dirty URL Validation

by Trevor Turk

I’ve come across a few different ways to validate URLs in my day, but they all seem a bit more complicated than necessary. Perhaps I’ll see the wisdom of these techniques soon, but for now it seems like there’s an easy solution to the problem:

class Link < ActiveRecord::Base

  attr_accessible :url
  validate :validate_url

private

  def validate_url
    errors.add(:url) unless %w(200 301 302).include?(Link.status_code(self.url))
  end

  def self.status_code(url)
    regexp = url.match(/https?://([^/]+)(.*)/)
    path = regexp[2].blank? ? '/' : regexp[2]
    Net::HTTP.start(regexp[1]) {|http| http.head(path).code}
  rescue
    nil
  end

end

Et VoilĂ .

Advertisement