Class: ActiveModel::Validations::IpValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/moca_rlibs/active_model_validators/ip.rb

Overview

IPアドレスのフォーマットをチェックする

Constant Summary collapse

PERMITTED_VERSION =
%i[v4 v6].freeze

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ IpValidator

Returns a new instance of IpValidator.



12
13
14
15
16
# File 'lib/moca_rlibs/active_model_validators/ip.rb', line 12

def initialize(options)
  options[:version] ||= %i[v4 v6]
  options[:version] = Array(options[:version])
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/moca_rlibs/active_model_validators/ip.rb', line 18

def validate_each(record, attribute, value)
  return if value.blank?

  value = value.presence.to_s
  return if options[:version].include?(:v4) && ::Resolv::IPv4::Regex.match?(value)
  return if options[:version].include?(:v6) && ::Resolv::IPv6::Regex.match?(value)

  record.errors.add('invalid ip format')
end