public function AdvbanAdmin::validateForm in Advanced ban 8
Form validation handler.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Overrides FormBase::validateForm
File
- src/
Form/ AdvbanAdmin.php, line 200
Class
- AdvbanAdmin
- Displays banned IP addresses.
Namespace
Drupal\advban\FormCode
public function validateForm(array &$form, FormStateInterface $form_state) {
$edit_mode = $form_state
->getValue('form_mode') == 'edit';
$ip = trim($form_state
->getValue('ip'));
$own_ip = $this
->getRequest()
->getClientIP();
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) {
// Check for a valid IP address.
$form_state
->setErrorByName('ip', $this
->t('Enter a valid IP address.'));
}
elseif (!$edit_mode && $this->ipManager
->isBanned($ip, [
'expiry_check' => FALSE,
])) {
// Check fpr already banned IP address.
$form_state
->setErrorByName('ip', $this
->t('This IP address is already banned.'));
}
elseif ($ip == $own_ip) {
// Check for own IP.
$form_state
->setErrorByName('ip', $this
->t('You may not ban your own IP address.'));
}
$ip_end = trim($form_state
->getValue('ip_end'));
// Range IP validate.
if (!empty($ip_end)) {
$own_ip_long = ip2long($own_ip);
if (filter_var($ip_end, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) {
// Check for a valid IP address.
$form_state
->setErrorByName('ip_end', $this
->t('Enter a valid IP address.'));
}
else {
$ip_long = ip2long($ip);
$ip_end_long = ip2long($ip_end);
if (!$ip_long || !$ip_end_long) {
if (!$ip_long) {
// Check for IP type.
$form_state
->setErrorByName('ip', $this
->t('Only IPv4 is available for IP range.'));
}
if (!$ip_end_long) {
// Check for IP type.
$form_state
->setErrorByName('ip_end', $this
->t('Only IPv4 is available for IP range.'));
}
}
elseif ($own_ip_long && $own_ip_long >= $ip_long && $own_ip_long <= $ip_end_long) {
$form_state
->setErrorByName('ip', $this
->t('You may not ban your own IP address %own_ip.', [
'%own_ip' => $own_ip,
]));
$form_state
->setErrorByName('ip_end', '');
}
elseif ($ip_end_long <= $ip_long) {
$form_state
->setErrorByName('ip', $this
->t('IP begin must be greater then IPThe end IP address must be greater than the start IP address.'));
$form_state
->setErrorByName('ip_end', '');
}
}
}
// Check for correct expiry duration.
$expiry_duration_index = $form_state
->getValue('expiry_duration');
if ($expiry_duration_index != AdvbanHelper::ADVBAN_NEVER) {
$expiry_duration = $this->ipManager
->expiryDurations($expiry_duration_index);
$expiry_date = strtotime($expiry_duration);
if (!$expiry_date) {
$form_state
->setErrorByName('expiry_date', $this
->t('Wrong expiry time with duration %expiry_duration', [
'%expiry_duration' => $expiry_duration,
]));
}
}
}