function datetime_datelist_validate

Validation callback for a datelist 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 element being processed.

array $form_state: The current state of the form.

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

File

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

Code

function datetime_datelist_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'] : '';

    // If there's empty input and the field is not required, set it to empty.
    if (empty($input['year']) && empty($input['month']) && empty($input['day']) && !$element['#required']) {
      form_set_value($element, NULL, $form_state);
    }
    elseif (empty($input['year']) && empty($input['month']) && empty($input['day']) && $element['#required']) {
      form_error($element, t('The %field date is required.'));
    }
    else {

      // If the input 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.'));
      }
    }
  }
}