You are here

public function IpAddressWidgetBase::validateIpAddressElement in IP address fields 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Field/FieldWidget/IpAddressWidgetBase.php \Drupal\field_ipaddress\Plugin\Field\FieldWidget\IpAddressWidgetBase::validateIpAddressElement()

Custom validator.

Parameters

array $element: The element being validated.

\Drupal\Core\Form\FormStateInterface $form_state: Current form state.

array $form: Current form.

File

src/Plugin/Field/FieldWidget/IpAddressWidgetBase.php, line 52

Class

IpAddressWidgetBase
Base class for the 'ipaddress_*' widgets.

Namespace

Drupal\field_ipaddress\Plugin\Field\FieldWidget

Code

public function validateIpAddressElement(array &$element, FormStateInterface $form_state, array $form) {
  $settings = $this->fieldDefinition
    ->getSettings();
  $value = trim($element['value']['#value']);
  if ($value === '') {
    return;
  }

  // Instantiate our IP, will throw \Exception if invalid.
  try {
    $ip_address = new IpAddress($value);
  } catch (\Exception $e) {

    // Make error messages a bit more relevant.
    if ($settings['allow_range']) {
      $form_state
        ->setError($element, t('Invalid IP or range.'));
    }
    else {
      $form_state
        ->setError($element, t('Invalid IP.'));
    }
    return;
  }
  if (!$settings['allow_range'] && $ip_address
    ->start() != $ip_address
    ->end()) {
    $form_state
      ->setError($element, t('Ranges not allowed, single IP only.'));
  }
  if ($settings['allow_family'] != IpAddress::IP_FAMILY_ALL && $settings['allow_family'] != $ip_address
    ->family()) {
    if ($settings['allow_family'] == IpAddress::IP_FAMILY_4) {
      $form_state
        ->setError($element, t('Only IPv4 addresses allowed.'));
    }
    else {
      $form_state
        ->setError($element, t('Only IPv6 addresses allowed.'));
    }
  }
  if ($settings['ip4_range'] && $ip_address
    ->family() == IpAddress::IP_FAMILY_4) {

    // No validation for $ip4_range here, it should have already been done
    // on field settings form.
    $range = new IpAddress($settings['ip4_range']);
    if (!$ip_address
      ->inRange($range
      ->start(), $range
      ->end())) {
      $form_state
        ->setError($element, t('IP must be within the range @min-@max', [
        '@min' => $range
          ->start(),
        '@max' => $range
          ->end(),
      ]));
    }
  }
  if ($settings['ip6_range'] && $ip_address
    ->family() == IpAddress::IP_FAMILY_6) {

    // No validation for $ip6_range here, it should have already been done
    // on field settings form.
    $range = new IpAddress($settings['ip6_range']);
    if (!$ip_address
      ->inRange($range
      ->start(), $range
      ->end())) {
      $form_state
        ->setError($element, t('IP must be within the range @min-@max', [
        '@min' => $range
          ->start(),
        '@max' => $range
          ->end(),
      ]));
    }
  }
}