Sha256: ef0cb6447fb39d9a404af69d582a8836c8e46a3b380edf2a1f5cf596f8fec601

Contents?: true

Size: 816 Bytes

Versions: 1

Compression:

Stored size: 816 Bytes

Contents

require 'localized_each_validator'

# Validates IPv4 and IPv6 addresses. Uses the @invalid_ip@ error message key.
#
# @example
#   validates :last_login_ip, ip_address: true
#
# h2. Options
#
# | @:ipv4_only@ | If @true@, IPv6 addresses are considered invalid. |
# | @:ipv6_only@ | If @true@, IPv4 addresses are considered invalid. |
# | @:message@ | A custom message to use if the IP is invalid. |
# | @:allow_nil@ | If true, @nil@ values are allowed. |

class IpAddressValidator < LocalizedEachValidator
  error_key :invalid_ip

  # @private
  def valid?(_, _, value)
    ip = nil
    begin
      ip = IPAddr.new(value)
    rescue ArgumentError
      return false
    end
    
    return false if ip.ipv4? and options[:ipv6_only]
    return false if ip.ipv6? and options[:ipv4_only]
    
    return true
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ip_address_validator-1.0.0 lib/ip_address_validator.rb