Created
June 18, 2014 20:26
-
-
Save zporter/913b983ba56155115e81 to your computer and use it in GitHub Desktop.
Rails: Full URL 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
class FullUrlValidator < ActiveModel::EachValidator | |
VALID_SCHEMES = %w(http https) | |
def validate_each(record, attribute, value) | |
unless valid_full_url?(value) | |
record.errors[attribute] << (options[:message] || 'is not a valid URL') | |
end | |
end | |
private | |
def valid_full_url?(url) | |
url = URI.parse(url) | |
url.scheme.in?(VALID_SCHEMES) && url.host | |
rescue URI::InvalidURIError | |
false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment