class ActiveModel::Validations::HostnameValidator

Constants

FINAL_LABEL_REGEXP
LABEL_REGEXP
RESERVED_OPTIONS

Public Instance Methods

validate_each(record, attribute, value) click to toggle source
# File lib/can_has_validations/validators/hostname_validator.rb, line 39
def validate_each(record, attribute, value)
  case options[:allow_ip]
  when 4, '4'
    return if value =~ Resolv::IPv4::Regex
  when 6, '6'
    return if value =~ Resolv::IPv6::Regex
  when true
    return if value =~ Resolv::IPv4::Regex || value =~ Resolv::IPv6::Regex
  end

  segments = options[:segments] || (2..100)
  segments = segments..segments if segments.is_a?(Integer)
  if defined?(Addressable::IDNA)
    value &&= Addressable::IDNA.to_ascii(value)
  end
  labels = value.split('.')

  is_valid = true
  is_valid &&= value.length <= 255
  is_valid &&= value !~ /\.\./
  is_valid &&= value !~ /_/ unless options[:allow_underscore]
  is_valid &&= value !~ %r{/} unless options[:allow_slash]
  is_valid &&= labels.size.in? segments
  labels.each_with_index do |label, idx|
    is_valid &&= label.length <= 63
    if !options[:skip_tld] && idx+1==labels.size
      is_valid &&= label =~ FINAL_LABEL_REGEXP
    elsif options[:allow_wildcard] && idx==0
      is_valid &&= label=='*' || label =~ LABEL_REGEXP
    else
      is_valid &&= label =~ LABEL_REGEXP
    end
  end

  unless is_valid
    record.errors.add(attribute, :invalid_hostname, **options.except(*RESERVED_OPTIONS).merge!(value: value))
  end
end