Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. Datetime.php

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 347

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']) {
            $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()) {
                $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,
                ]));
            }
        }
    }
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal