Class: IpAddressValidator

Inherits:
LocalizedEachValidator
  • Object
show all
Defined in:
lib/ip_address_validator.rb

Overview

Validates IPv4 and IPv6 addresses. Uses the ‘invalid_ip` error message key.

Options


| | | |:—————-|:————————————————————-| | ‘:ipv4_only` | If `true`, IPv6 addresses are considered invalid. | | `:ipv6_only` | If `true`, IPv4 addresses are considered invalid. | | `:allow_cidr` | If `true`, CIDR notation (e.g. `10.0.0.0/24`) is allowed. | | | Defaults to `false`, so values containing `/` are rejected. | | `:no_loopback` | If `true`, loopback addresses (e.g. `127.0.0.1`, `::1`) | | | are considered invalid. | | `:no_private` | If `true`, RFC 1918 / unique local addresses (e.g. | | | `10.0.0.0/8`, `fc00::/7`) are considered invalid. | | `:no_reserved` | If `true`, reserved addresses (link-local, multicast, | | | unspecified, etc.) are considered invalid. | | `:message` | A custom message to use if the IP is invalid. | | `:allow_nil` | If `true`, `nil` values are allowed. | | `:allow_blank` | If `true`, blank values are allowed. |

Examples:

validates :last_login_ip, ip_address: true

Constant Summary collapse

VERSION =
IpAddressValidatorGem::VERSION

Instance Method Summary collapse

Instance Method Details

#valid?(_record, _attribute, value) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/ip_address_validator.rb', line 41

def valid?(_record, _attribute, value)
  return false unless value.is_a?(String)
  return false if !options[:allow_cidr] && value.include?("/")

  ip =
    begin
      IPAddr.new(value)
    rescue IPAddr::Error, ArgumentError
      return false
    end

  return false if ip.ipv4? && options[:ipv6_only]
  return false if ip.ipv6? && options[:ipv4_only]

  return false if options[:no_loopback] && ip.loopback?
  return false if options[:no_private] && private_ip?(ip)
  return false if options[:no_reserved] && reserved_ip?(ip)

  true
end