domain_validator.rb 935 B

123456789101112131415161718192021222324252627282930
  1. # frozen_string_literal: true
  2. class DomainValidator < ActiveModel::EachValidator
  3. MAX_DOMAIN_LENGTH = 256
  4. MIN_LABEL_LENGTH = 1
  5. MAX_LABEL_LENGTH = 63
  6. ALLOWED_CHARACTERS_RE = /^[a-z0-9\-]+$/i
  7. def validate_each(record, attribute, value)
  8. return if value.blank?
  9. (options[:multiline] ? value.split : [value]).each do |domain|
  10. _, domain = domain.split('@') if options[:acct]
  11. next if domain.blank?
  12. record.errors.add(attribute, options[:multiline] ? :invalid_domain_on_line : :invalid, value: domain) unless compliant?(domain)
  13. end
  14. end
  15. private
  16. def compliant?(value)
  17. uri = Addressable::URI.new
  18. uri.host = value
  19. uri.normalized_host.size < MAX_DOMAIN_LENGTH && uri.normalized_host.split('.').all? { |label| label.size.between?(MIN_LABEL_LENGTH, MAX_LABEL_LENGTH) && label =~ ALLOWED_CHARACTERS_RE }
  20. rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError
  21. false
  22. end
  23. end