Created
April 29, 2011 19:37
-
-
Save joshuap/948880 to your computer and use it in GitHub Desktop.
Net:HTTP enabled URI Validator for Rails 3
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 'uri_validator' |
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
validates :url, :presence => true, :uri => { :format => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix } |
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' | |
# Thanks Ilya! http://www.igvita.com/2006/09/07/validating-url-in-ruby-on-rails/ | |
# 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 UriValidator < ActiveModel::EachValidator | |
def validate_each(object, attribute, value) | |
raise(ArgumentError, "A regular expression must be supplied as the :format option of the options hash") unless options[:format].nil? or options[:format].is_a?(Regexp) | |
configuration = { :message => "is invalid or not responding", :format => URI::regexp(%w(http https)) } | |
configuration.update(options) | |
if value =~ configuration[:format] | |
begin # check header response | |
case Net::HTTP.get_response(URI.parse(value)) | |
when Net::HTTPSuccess then true | |
else object.errors.add(attribute, configuration[:message]) and false | |
end | |
rescue # Recover on DNS failures.. | |
object.errors.add(attribute, configuration[:message]) and false | |
end | |
else | |
object.errors.add(attribute, configuration[:message]) and false | |
end | |
end | |
end |
@Server4001 you could easily add support to the regex for ftp://
. Something like:
validates :url, :presence => true, :uri => { :format => URI::regexp(%w(http https ftp)) }
However, I think the Net::HTTP request would fail for FTP uris. You would need to modify the validator to check the validity of the FTP server.
Enter only url i.e http://www.flipkart.com then it doesnot validate it. It should also check if it is not a proper image url
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No support for ftp://.... ?