Class: ActiveModel::Validations::HostnameValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/can_has_validations/validators/hostname_validator.rb

Constant Summary collapse

LABEL_REGEXP =
/\A([a-zA-Z0-9_]([a-zA-Z0-9_-]+)?)?[a-zA-Z0-9]\z/
FINAL_LABEL_REGEXP =
/\A(xn--[a-zA-Z0-9]{2,}|[a-zA-Z]{2,})\z/

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/can_has_validations/validators/hostname_validator.rb', line 34

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 &&= labels.size.in? segments
  labels.each_with_index do |label, idx|
    is_valid &&= label.length <= 63
    if 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)
  end
end