You are here

public function DateFilter::datelistValidate in Visitors 8.2

Validates the date type to prevent invalid dates (e.g., February 30, 2006).

If the date is valid, the date is set in the form as a string using the format designated in __toString().

File

src/Form/DateFilter.php, line 156

Class

DateFilter

Namespace

Drupal\visitors\Form

Code

public function datelistValidate($element, FormStateInterface $form_state) {
  $input_exists = FALSE;
  $input = NestedArray::getValue($form_state
    ->getValues(), $element['#parents'], $input_exists);
  if (!$input_exists) {
    return;
  }

  // If there's empty input, set an error.
  if (empty($input['year']) || empty($input['month']) || empty($input['day'])) {
    $form_state
      ->setError($element, $this
      ->t('The %field date is required.'));
    return;
  }
  if (!checkdate($input['month'], $input['day'], $input['year'])) {
    $this
      ->setError($element, $this
      ->t('The specified date is invalid.'));
    return;
  }
  $date = DrupalDateTime::createFromArray($input);
  if ($date instanceof DrupalDateTime && !$date
    ->hasErrors()) {
    $form_state
      ->setValueForElement($element, $date);
    return;
  }
  $form_state
    ->setError($element, $this
    ->t('The %field date is invalid.'));
}