Sha256: 452a71753a4d582ac4f7c5d7195b41361f0fe103284ecd34872f2e11547f55c4

Contents?: true

Size: 1.23 KB

Versions: 5

Compression:

Stored size: 1.23 KB

Contents

require 'uri'
class UrlValidator < ActiveModel::EachValidator

  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

  DEFAULT_SCHEMES = [:http, :https]

  def valid_domain?(value, options)
    value_downcased = value.host.to_s.downcase
    options.empty? || options.any? { |domain| value_downcased.end_with?(".#{domain.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? { |scheme| value_downcased == scheme.to_s.downcase }
  end

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

  def valid_uri?(value)
    value.kind_of?(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

5 entries across 5 versions & 1 rubygems

Version Path
active_validation-2.2.2 lib/active_validation/validators/url_validator.rb
active_validation-2.2.1 lib/active_validation/validators/url_validator.rb
active_validation-2.2.0 lib/active_validation/validators/url_validator.rb
active_validation-2.0.1 lib/active_validation/validators/url_validator.rb
active_validation-2.0.0 lib/active_validation/validators/url_validator.rb