Sha256: 85cb4ea6f8ae2f4fa7b8c9a4f783e874f370f9d2c6f498113d16f066ed05bb18

Contents?: true

Size: 1.24 KB

Versions: 7

Compression:

Stored size: 1.24 KB

Contents

require 'uri'
class UrlValidator < ActiveModel::EachValidator

  DEFAULT_SCHEMES ||= [:http, :https].freeze

  def validate_each(record, attribute, value)
    uri = URI.parse(value.to_s)
    raise URI::InvalidURIError unless valid?(uri, options)
  rescue URI::InvalidURIError
    record.errors[attribute] <<
      (options[:message] || I18n.t('active_validation.errors.messages.url'))
  end

  private

  def valid_domain?(value, options)
    value_downcased = value.host.to_s.downcase
    options.empty? || options.any? { |dom| value_downcased.end_with?(".#{dom.downcase}") }
  end

  def valid_length?(value)
    value.present?
  end

  def valid_scheme?(value, options)
    value_downcased = value.scheme.to_s.downcase
    options.empty? || options.any? { |sch| value_downcased == sch.to_s.downcase }
  end

  def valid_root?(value)
    ['/', ''].include?(value.path) && value.query.blank? && value.fragment.blank?
  end

  def valid_uri?(value)
    value.is_a?(URI::Generic)
  end

  def valid?(value, options)
    valid_length?(value) &&
      valid_uri?(value) &&
      valid_domain?(value, [*(options[:domain])]) &&
      valid_scheme?(value, [*(options[:scheme] || UrlValidator::DEFAULT_SCHEMES)]) &&
      (options[:root] ? valid_root?(value) : true)
  end

end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
active_validation-4.0.7 lib/active_validation/validators/url_validator.rb
active_validation-4.0.6 lib/active_validation/validators/url_validator.rb
active_validation-4.0.5 lib/active_validation/validators/url_validator.rb
active_validation-4.0.4 lib/active_validation/validators/url_validator.rb
active_validation-4.0.3 lib/active_validation/validators/url_validator.rb
active_validation-4.0.2 lib/active_validation/validators/url_validator.rb
active_validation-4.0.1 lib/active_validation/validators/url_validator.rb