Class: UrlValidator

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

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/validators/url_validator.rb', line 4

def validate_each(record, attribute, value)
  if value.present?
    valid =
      begin
        uri = URI.parse(value)
        uri.is_a?(URI::HTTP) && !uri.host.nil? && uri.host.include?(".")
      rescue URI::Error => e
        if (e.message =~ /URI must be ascii only/)
          value = UrlHelper.encode(value)
          retry
        end

        nil
      end

    unless valid
      record.errors.add(attribute, options[:message] || I18n.t("errors.messages.invalid"))
    end
  end
end