Class: Incline::IpAddressValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/incline/validators/ip_address_validator.rb

Overview

Validates a string contains a valid IP address.

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Validates attributes to determine if the values contain valid IP addresses.

Set the :no_mask option to restrict the IP address to singular addresses only.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/incline/validators/ip_address_validator.rb', line 12

def validate_each(record, attribute, value)
  begin
    unless value.blank?
      IPAddr.new(value)
      if options[:no_mask]
        if value =~ /\//
          record.errors[attribute] << (options[:message] || 'must not contain a mask')
        end
      elsif options[:require_mask]
        unless value =~ /\//
          record.errors[attribute] << (options[:message] || 'must contain a mask')
        end
      end
    end
  rescue IPAddr::InvalidAddressError
    record.errors[attribute] << (options[:message] || 'is not a valid IP address')
  end
end