Created
January 21, 2010 00:48
-
-
Save maxschulze/282480 to your computer and use it in GitHub Desktop.
Rails URL Validation with :allow_blank
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
# Original credits: http://blog.inquirylabs.com/2006/04/13/simple-uri-validation/ | |
# HTTP Codes: http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTPResponse.html | |
class ActiveRecord::Base | |
def self.validates_uri_existence_of(*attr_names) | |
configuration = { :message => "is not valid or not responding", :on => :save, :with => nil } | |
configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash) | |
configuration[:with] = /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix | |
validates_each(attr_names, configuration) do |r, a, v| | |
if v.blank? && configuration[:allow_blank] | |
return true | |
end | |
if v.to_s =~ configuration[:with] # check RegExp | |
begin # check header response | |
case Net::HTTP.get_response(URI.parse(v)) | |
when Net::HTTPSuccess then true | |
else r.errors.add(a, configuration[:message]) and false | |
end | |
rescue # Recover on DNS failures.. | |
r.errors.add(a, configuration[:message]) and false | |
end | |
else | |
r.errors.add(a, configuration[:message]) and false | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment