function datetime_datetime_validate

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.

array $form_state: The current state of the form.

1 string reference to 'datetime_datetime_validate'
datetime_element_info in drupal/core/modules/datetime/datetime.module
Implements hook_element_info().

File

drupal/core/modules/datetime/datetime.module, line 654
Field hooks to implement a simple datetime field.

Code

function datetime_datetime_validate($element, &$form_state) {
  $input_exists = FALSE;
  $input = NestedArray::getValue($form_state['values'], $element['#parents'], $input_exists);
  if ($input_exists) {
    $title = !empty($element['#title']) ? $element['#title'] : '';
    $date_format = $element['#date_date_element'] != 'none' ? datetime_html5_format('date', $element) : '';
    $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $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_set_value($element, NULL, $form_state);
    }
    elseif (empty($input['date']) && empty($input['time']) && $element['#required']) {
      form_error($element, t('The %field date is required. Please enter a date in the format %format.', array(
        '%field' => $title,
        '%format' => datetime_format_example($format),
      )));
    }
    else {

      // If the date is valid, set it.
      $date = $input['object'];
      if ($date instanceof DrupalDateTime && !$date
        ->hasErrors()) {
        form_set_value($element, $date, $form_state);
      }
      else {
        form_error($element, t('The %field date is invalid. Please enter a date in the format %format.', array(
          '%field' => $title,
          '%format' => datetime_format_example($format),
        )));
      }
    }
  }
}