public function IpAddressField::validateIpAddressElement in IP address fields 2.0.x
Same name and namespace in other branches
- 8 src/Plugin/Field/FieldType/IpAddressField.php \Drupal\field_ipaddress\Plugin\Field\FieldType\IpAddressField::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/ FieldType/ IpAddressField.php, line 205
Class
- IpAddressField
- Plugin implementation of the 'ipaddress' field type.
Namespace
Drupal\field_ipaddress\Plugin\Field\FieldTypeCode
public function validateIpAddressElement(array &$element, FormStateInterface $form_state, array $form) {
$value = $form_state
->getValue($element['#parents']);
if (trim($value) == '') {
return;
}
// Instantiate our IP, will throw \Exception if invalid.
try {
$ip_address = new IpAddress($value);
} catch (\Exception $e) {
$form_state
->setError($element, t('Invalid IP or range.'));
return;
}
// These fields can only accept IP ranges.
if ($ip_address
->start() == $ip_address
->end()) {
$form_state
->setError($element, t('Value must be an IP range.'));
}
if ($element['#name'] == 'settings[ip4_range]' && $ip_address
->family() != IpAddress::IP_FAMILY_4) {
$form_state
->setError($element, t('Value must be an IPv4 range.'));
}
if ($element['#name'] == 'settings[ip6_range]' && $ip_address
->family() != IpAddress::IP_FAMILY_6) {
$form_state
->setError($element, t('Value must be an IPv6 range.'));
}
}