You are here

function _field_ipaddress_validate_cidr in IP address fields 7

Validate a CIDR input.

The IP address (without CIDR prefix) is assumed to be the start of one well-defined block.

1 string reference to '_field_ipaddress_validate_cidr'
field_ipaddress_field_widget_form in ./field_ipaddress.module
Implements hook_field_widget_form().

File

./field_ipaddress.module, line 230

Code

function _field_ipaddress_validate_cidr($element, &$form_state) {
  $delta = $element['#delta'];
  $lang_code = $element['#language'];
  $field = $form_state['field'][$element['#field_name']][$lang_code]['field'];
  $field_name = $field['field_name'];
  $ipaddress = trim($form_state['values'][$field_name][$lang_code][$delta]['start']);
  if (!empty($ipaddress)) {
    list($ip, $bits) = explode('/', $ipaddress);
    $minimumprefix = _field_ipaddress_minimum_cidr_prefix(ip2long($ip), 32);
    if (!is_numeric($bits) || (int) $bits != $bits || $bits < 0 || $bits > 32) {
      form_error($element, t('The prefix must be an integer between 0 and 32.'));
    }
    else {
      if ($bits < $minimumprefix) {
        form_error($element, t('The prefix is too small for the given IP address. ' . 'The minimum prefix is @value.', array(
          '@value' => $minimumprefix,
        )));
      }
      else {
        $range = _field_ipaddress_cidr2long($ipaddress);
        if ($range) {
          form_set_value($element, $range, $form_state);
        }
        else {
          form_error($element, t('Invalid IP range or address.'));
        }
      }
    }
  }
}