public static Datetime::validateDatetime(&$element, FormStateInterface $form_state, &$complete_form)
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.
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.
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 = !empty($element['#title']) ? $element['#title'] : ''; $date_format = $element['#date_date_element'] != 'none' ? static::getHtml5DateFormat($element) : ''; $time_format = $element['#date_time_element'] != 'none' ? static::getHtml5TimeFormat($element) : ''; $format = trim($date_format . ' ' . $time_format); // 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); } // If there's empty input and the field is required, set an error. A // reminder of the required format in the message provides a good UX. elseif (empty($input['date']) && empty($input['time']) && $element['#required']) { $form_state->setError($element, t('The %field date is required. Please enter a date in the format %format.', array('%field' => $title, '%format' => static::formatExample($format)))); } else { // If the date is valid, set it. $date = $input['object']; if ($date instanceof DrupalDateTime && !$date->hasErrors()) { $form_state->setValueForElement($element, $date); } // If the date is invalid, set an error. A reminder of the required // format in the message provides a good UX. else { $form_state->setError($element, t('The %field date is invalid. Please enter a date in the format %format.', array('%field' => $title, '%format' => static::formatExample($format)))); } } } }
© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Datetime!Element!Datetime.php/function/Datetime::validateDatetime/8.1.x