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
71
72
73
74
75
76
77
78
79
|
# File 'lib/can_has_validations/validators/hostname_validator.rb', line 39
def validate_each(record, attribute, value)
value = value.to_s
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] || (options[:skip_tld] ? 1..100 : 2..100)
segments = segments..segments if segments.is_a?(Integer)
if defined?(Addressable::IDNA)
value &&= Addressable::IDNA.to_ascii(value)
end
labels = value.split('.', -1)
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]==:multi && idx==0
is_valid &&= %w(** *).include?(label) || label =~ 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
|