вівторок, 12 березня 2013 р.

Rails 3 validations

Validate URL 

(from https://gist.github.com/bluemont/2986523 and http://stackoverflow.com/questions/7167895/whats-a-good-way-to-validate-links-urls-in-rails-3)

Put this into app/validators

class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
valid = begin
URI.parse(value).kind_of?(URI::HTTP)
rescue URI::InvalidURIError
false
end
unless valid
record.errors[attribute] << (options[:message] || "is an invalid URL")
end
end
end

Usage

validates :url, :presence => true, :url => true