function Datetime::validateDatetime

Validation callback for a datetime element.

If the date is valid, the date object created from the user input is set in the form for use by the caller. The work of compiling the user input back into a date object is handled by the value callback, so we can use it here. We also have the raw input available for validation testing.

Parameters

array $element: The form element whose value is being validated.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

array $complete_form: The complete form structure.

File

core/lib/Drupal/Core/Datetime/Element/Datetime.php, line 367

Class

Datetime
Provides a datetime element.

Namespace

Drupal\Core\Datetime\Element

Code

public static function validateDatetime(&$element, FormStateInterface $form_state, &$complete_form) {
  $input_exists = FALSE;
  $input = NestedArray::getValue($form_state->getValues(), $element['#parents'], $input_exists);
  if ($input_exists) {
    $title = static::getElementTitle($element, $complete_form);
    // If there's empty input and the field is not required, set it to empty.
    if (empty($input['date']) && empty($input['time']) && !$element['#required']) {
      $form_state->setValueForElement($element, NULL);
    }
    elseif (empty($input['date']) && empty($input['time']) && $element['#required']) {
      if (isset($element['#required_error'])) {
        $form_state->setError($element, $element['#required_error']);
      }
      else {
        $form_state->setError($element, t('The %field date is required.', [
          '%field' => $title,
        ]));
      }
    }
    else {
      // If the date is valid, set it.
      $date = $input['object'];
      if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
        $range = static::datetimeRangeYears($element['#date_year_range']);
        $min = DrupalDateTime::createFromArray([
          'year' => $range[0],
        ], $date->getTimezone());
        $max = DrupalDateTime::createFromArray([
          'year' => $range[1] + 1,
        ], $date->getTimezone());
        // Validate the date. It's valid if it's within the valid year range.
        if ($date->getTimestamp() < $min->getTimestamp() || $date->getTimestamp() >= $max->getTimestamp()) {
          $form_state->setError($element, t('The %field date is invalid. Date should be in the %min-%max year range.', [
            '%field' => $title,
            '%min' => $range[0],
            '%max' => $range[1],
          ]));
        }
        else {
          $form_state->setValueForElement($element, $date);
        }
      }
      else {
        $form_state->setError($element, t('The %field date is invalid. Enter a date in the correct format.', [
          '%field' => $title,
        ]));
      }
    }
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.