Sha256: af3ed22c24182922e8fc7d98cfb23b6d53dd83780ca74f2bbd90628a3320033e

Contents?: true

Size: 1.08 KB

Versions: 2

Compression:

Stored size: 1.08 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('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

2 entries across 2 versions & 1 rubygems

Version Path
flash_validators-3.0.1 lib/flash_validators/validators/url_validator.rb
flash_validators-3.0.0 lib/flash_validators/validators/url_validator.rb