Class: IpCidrFormatValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/ip_cidr_format_validator.rb

Overview

Validates IP addresses and CIDR notation.

Supports:

  • IPv4: 192.168.1.1
  • IPv6: ::1, 2001:db8::1
  • CIDR: 192.168.1.0/24, 10.0.0.0/8

Usage in model:
validates :ip_list, ip_cidr_format: true

For array fields:
validates :ip_list, ip_cidr_format: { array: true }

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/validators/ip_cidr_format_validator.rb', line 19

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

  values = options[:array] ? Array(value) : [value]

  values.each do |v|
    next if v.blank?

    unless valid_ip_or_cidr?(v.to_s.strip)
      record.errors.add(
        attribute,
        options[:message] || "'#{v}' is not a valid IP address or CIDR notation"
      )
    end
  end
end