Class: ActiveModel::Validations::IpAddressValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/active_model/validations/ip_address_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attr_name, value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/active_model/validations/ip_address_validator.rb', line 4

def validate_each(record, attr_name, value)
  # do not validate if value is empty
  return if value.nil?

  @validator = ::Validator::IpAddress.new(value)

  # validate IPv4 or IPv6 if they are only allowed
  if options[:only] and [:ipv4, :ipv6].include?(options[:only])
    if options[:only] == :ipv4 and !@validator.valid_ipv4?
      record.errors.add(attr_name, :"ip_address.invalid.ipv4", options)
      return
    end
    if options[:only] == :ipv6 and !@validator.valid_ipv6?
      record.errors.add(attr_name, :"ip_address.invalid.ipv6", options)
      return
    end
  end

  if options[:allow_prefix] == true and @validator.has_prefix?
    unless @validator.valid_prefix?
      record.errors.add(attr_name, :"ip_address.prefix_invalid.#{@validator.is_ipv4? ? "ipv4" : "ipv6"}", options)
      return 
    end
  elsif @validator.has_prefix?
    record.errors.add(attr_name, :'ip_address.prefix_disallowed', options)
    return
  end

  unless @validator.valid?
    record.errors.add(attr_name, :'ip_address.invalid.general', options)
  end
end