Class: IpAddressValidator

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

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



2
3
4
5
6
# File 'lib/graph_starter/ip_address_validator.rb', line 2

def validate_each(record, attribute, value)
  message = validation_message(value)

  record.errors.add attribute, message if message
end

#validation_message(value) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/graph_starter/ip_address_validator.rb', line 8

def validation_message(value)
  match = value.to_s.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)

  if match
    if !value.split('.').all? { |segment| segment.to_i.in?(0..255) }
      'segments must be between 0 and 255'
    end
  else
    'must match IP address pattern'
  end
end