app/validators/ip_format_validator.rb in metasploit-model-3.0.0 vs app/validators/ip_format_validator.rb in metasploit-model-3.1.0
- old
+ new
@@ -1,31 +1,25 @@
require 'ipaddr'
-# Validates that value is an IPv4 or IPv6 address.
+# Validates that value is a valid IPv4 or IPv6 address.
class IpFormatValidator < ActiveModel::EachValidator
- # Validates that `value` is an IPv4 or IPv4 address. Ranges in CIDR or netmask notation are not allowed.
+ # Validates that `attribute`'s `value` on `object` is a valid IPv4 or IPv6 address.
#
# @param record [#errors, ApplicationRecord] ActiveModel or ActiveRecord
# @param attribute [Symbol] name of IP address attribute.
# @param value [String, nil] IP address.
# @return [void]
- # @see IPAddr#ipv4?
- # @see IPAddr#ipv6?
- def validate_each(record, attribute, value)
+ def validate_each(object, attribute, value)
+ error_message_block = lambda{ object.errors.add attribute, "must be a valid IPv4 or IPv6 address" }
begin
- potential_ip = IPAddr.new(value)
- rescue ArgumentError
- record.errors[attribute] << 'must be a valid IPv4 or IPv6 address'
- else
- # if it includes a netmask, then it's not an IP address, but an IP range.
- if potential_ip.ipv4?
- if potential_ip.instance_variable_get(:@mask_addr) != IPAddr::IN4MASK
- record.errors[attribute] << 'must be a valid IPv4 or IPv6 address and not an IPv4 address range in CIDR or netmask notation'
- end
- elsif potential_ip.ipv6?
- if potential_ip.instance_variable_get(:@mask_addr) != IPAddr::IN6MASK
- record.errors[attribute] << 'must be a valid IPv4 or IPv6 address and not an IPv6 address range in CIDR or netmask notation'
- end
+ if value.is_a? IPAddr
+ potential_ip = value.dup
+ else
+ potential_ip = IPAddr.new(value)
end
+
+ error_message_block.call unless potential_ip.ipv4? || potential_ip.ipv6?
+ rescue ArgumentError
+ error_message_block.call
end
end
end