Created
May 3, 2011 11:31
-
-
Save kuahyeow/953192 to your computer and use it in GitHub Desktop.
URL validator for Rails 3 - kuahyeow
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 this file, or put this in where Rails will auto load it. | |
class UrlValidator < ActiveModel::EachValidator | |
def initialize(options) | |
super | |
@domain = options[:domain] | |
@permissible_schemes = options[:schemes] || %w(http https) | |
@error_message = options[:message] || 'is not a valid url' | |
end | |
def validate_each(record, attribute, value) | |
if URI::regexp(@permissible_schemes).match(value) | |
begin | |
uri = URI.parse(value) | |
if @domain | |
record.errors.add(attribute, 'does not belong to domain', :value => value) unless uri.host == @domain || uri.host.ends_with?(".#{@domain}") | |
end | |
rescue URI::InvalidURIError | |
record.errors.add(attribute, @error_message, :value => value) | |
end | |
else | |
record.errors.add(attribute, @error_message, :value => value) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Pass in a domain to validate a url belongs to a domain (including any sub-domains and pages beneath the domain and sub-domains)