Sha256: 25f062767fa3544457e0a3bf3b308ebc1095fe1b2810448cf4c8757eb10210c0

Contents?: true

Size: 1.1 KB

Versions: 11

Compression:

Stored size: 1.1 KB

Contents

require 'uri'
class UrlValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    uri = URI.parse(value)
    raise URI::InvalidURIError unless valid?(uri, options)
  rescue URI::InvalidURIError
    record.errors[attribute] << (options[:message] || I18n.t('flash_validators.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_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?(value, options)
    value.kind_of?(URI::Generic) &&
    valid_domain?(value, [*(options[:domain])]) &&
    valid_scheme?(value, [*(options[:scheme] || UrlValidator::DEFAULT_SCHEMES)]) &&
    (options[:root] ? valid_root?(value) : true)
  end

end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
flash_validators-3.0.12 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.11 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.10 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.9 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.8 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.7 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.6 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.5 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.4 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.3 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.2 lib/flash_validators/validators/url_validator.rb