Created
September 22, 2013 11:47
-
-
Save hendricius/6659198 to your computer and use it in GitHub Desktop.
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
class UrlValidator < ActiveModel::EachValidator | |
# Credits to Lee Machin https://coderwall.com/p/ztig5g | |
# Place this in app/validators/url_validator.rb | |
def validate_each(record, attribute, value) | |
record.errors[attribute] << (options[:message] || I18n.t(:must_be_valid_url)) unless url_valid?(value) | |
end | |
def url_valid?(url) | |
self.class.url_valid?(url) | |
end | |
# A URL may be technically well-formed but may | |
# not actually be valid, so this checks for both. | |
# Use in models like: | |
# UrlValidator.url_valid?("foo") | |
# => false | |
def self.url_valid?(url) | |
url = URI.parse(url) rescue false | |
url.kind_of?(URI::HTTP) || url.kind_of?(URI::HTTPS) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment