Posts for: #Validations

Rails: How To Create Custom Validations

Often our model objects leaning toward to be confused or noisy, due to validations DSLs. Imagine a class Answer, with an attribute, that should be exactly a string representation of a boolean. Ok, I know it’s an odd example, but: it’s trivial enough to make this example clear, and.. It happened to me to deal with this situation. :-P

class Answer %w( true false ), :message => "Should be exactly true or false." end

[]

Ruby on Rails: Validate URL

Hi, just a snippet to validate an url with Ruby on Rails.

class WebSite /^((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
[]