DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ilya has posted 1 posts at DZone. View Full User Profile

URL/URI Validations In Rails

09.08.2006
| 6847 views |
  • submit to reddit
        Here is a quick/basic URI validation library for your Rails app: 

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)
    
    raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
    
    validates_each(attr_names, configuration) do |r, a, v|
        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

Save the code above into a file in your 'lib' directory. ex: validates_uri_existence_of.rb. Include the file in your environment.rb (ex: require 'validates_uri_existence_of'). 

And now you can use the validator in any model by calling:
validates_uri_existence_of :url, :with =>
        /(^$)|(^(http|https)://[a-z0-9] ([-.]{1}[a-z0-9] )*.[a-z]{2,5}(([0-9]{1,5})?/.*)?$)/ix

Above code validates the URI/URL against a regular expression first, and then does a HEAD query to confirm that the page is alive (HTTPSuccess code is returned). You could easily modify the code to extend the functionality as you wish. 

More info in <a href="http://www.igvita.com/blog/2006/09/07/validating-url-in-ruby-on-rails/"> this post.</a>