Class: IpFormatValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- IpFormatValidator
- Defined in:
- app/validators/ip_format_validator.rb
Overview
Validates that value is an IPv4 or IPv6 address.
Instance Method Summary collapse
-
#validate_each(record, attribute, value) ⇒ void
Validates that
value
is an IPv4 or IPv4 address.
Instance Method Details
#validate_each(record, attribute, value) ⇒ void
This method returns an undefined value.
Validates that value
is an IPv4 or IPv4 address. Ranges in CIDR or netmask notation are not allowed.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'app/validators/ip_format_validator.rb', line 13 def validate_each(record, attribute, value) 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 end end end |