Netmask validator

Sharing the wealth. I just finished working on a custom netmask
validator and thought others might benefit. Of course, comments and
suggestions are welcome.

def validates_netmask(*attr_names)
configuration = { :only_numbers => ‘must only use numbers as octet
:range => ‘has one or more octet values that are >
:invalid => ‘is invalid’ }
configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)

validates_each attr_names do |record, attr_name, value|
# Test for non-numeric values
record.errors.add(attr_name, configuration[:only_numbers]) unless’.’, ‘’) =~ /^\d+$/

# Make binary string from octets
binary = ''
value.split('.').each do |octet|
  binary << '%08b' % octet

# Test for octet values > 255
record.errors.add(attr_name, configuration[:range]) if binary.length 


# Test for valid netmask (contiguous binary string of 1's)
record.errors.add(attr_name, configuration[:invalid]) if

binary.include? ‘01’

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs