Class: ActiveModel::Validations::UrlValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/custom_validations/url_validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UrlValidator

Returns a new instance of UrlValidator.



7
8
9
10
# File 'lib/custom_validations/url_validator.rb', line 7

def initialize(options)
  options[:as_host] = false if options[:as_host].blank?
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/custom_validations/url_validator.rb', line 12

def validate_each(record, attribute, value)
  return if value.to_s.blank? # it doesn't validate presence

  valid = begin
    uri = URI.parse(value)
    uri.kind_of?(URI::HTTP) and !uri.host.to_s.match /^\./
  rescue URI::InvalidURIError
    false
  end


  if options[:as_host] and uri.kind_of?(URI::Generic)
    if uri.scheme.present? or value.match(/\?|\/|\:|^\s*\./)
      record.errors.add(attribute, :url_as_host, options)
    end

  elsif !valid
    record.errors.add(attribute, :url, options)
  end

end