Class: HrefSanitizer::UrlValidator

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

Constant Summary collapse

EMAIL_REGEXP =
/\A[^@\s]+@[^@\s]+\z/

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/href_sanitizer/url_validator.rb', line 24

def validate_each(record, attribute, value)
  stripped = value.to_s.strip

  # Accept bare email addresses when accept_email: true
  if options.fetch(:accept_email, false) && stripped.match?(EMAIL_REGEXP)
    return
  end

  uri = parse(stripped)
  unless uri
    record.errors.add(attribute, options.fetch(:message, :url))
    return
  end

  allowed_schemes = options.fetch(:schemes, %w[http https])
  unless uri.scheme&.downcase&.in?(allowed_schemes)
    record.errors.add(attribute, options.fetch(:message, :url))
    return
  end

  unless HrefSanitizer::UrlSanitizer.allowed_uri?(stripped)
    record.errors.add(attribute, options.fetch(:message, :url))
    return
  end

  if options.fetch(:no_local, false)
    unless HrefSanitizer::UrlSanitizer.public_url?(stripped)
      record.errors.add(attribute, options.fetch(:message, :private_ip_url))
    end
  end
end