Class: UrlValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- UrlValidator
- Defined in:
- lib/href_sanitizer/url_validator.rb
Overview
ActiveModel validator for URLs. Registered as ‘url:` so it’s a drop-in replacement for custom URLValidators.
Usage:
validates :website, url: true
validates :website, url: { no_local: true }, allow_blank: true
validates :website, url: { schemes: %w[https] }
validates :lien_dpo, url: { accept_email: true }
Class name is UrlValidator, but we also alias as URLValidator to support apps with ‘inflect.acronym ’URL’‘ (which makes Rails resolve `validates :field, url: true` to URLValidator).
Constant Summary collapse
- EMAIL_REGEXP =
/\A[^@\s]+@[^@\s]+\z/
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
23 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 |
# File 'lib/href_sanitizer/url_validator.rb', line 23 def validate_each(record, attribute, value) stripped = value.to_s.strip # Accept bare email addresses when accept_email: true if .fetch(:accept_email, false) && stripped.match?(EMAIL_REGEXP) return end uri = parse(stripped) unless uri record.errors.add(attribute, .fetch(:message, :url)) return end allowed_schemes = .fetch(:schemes, %w[http https]) unless uri.scheme&.downcase&.in?(allowed_schemes) record.errors.add(attribute, .fetch(:message, :url)) return end unless HrefSanitizer::UrlSanitizer.allowed_uri?(stripped) record.errors.add(attribute, .fetch(:message, :url)) return end if .fetch(:no_local, false) unless HrefSanitizer::UrlSanitizer.public_url?(stripped) record.errors.add(attribute, .fetch(:message, :private_ip_url)) end end end |