I came across this issue while using a date_popup form element with the format d-M-Y (e.g., 14-Nov-2014). If the user types the date in the field with any capitalization scheme other than the first letter in uppercase and the next two in lowercase, the field value doesn't pass the date_popup validation. For example, "Nov" works, but "NOV" and "nov" do not. The attached patch allows month names (full and abbreviated) regardless of the case to be used to create DateObjects, and thus also solves the date_popup form validation problem.

Comments

ChrisLaFrancis’s picture

If anyone is curious, as a workaround for this issue I created the following function and added it to the date_popup element's '#element_validate' attribute. It gets called before date_popup_validate() so it can fix the case if necessary.

function my_module_date_popup_element_validation_helper($element, &$form_state) {
  // Get the date value from the passed-in element.
  $date = $element['#value']['date'];

  // If the value isn't in the proper format (d-M-Y), we don't need to do
  // anything here since date_popup_validate() will handle it.
  if (empty($date) || !preg_match('/^\d{1,2}\-[a-zA-Z]{3}\-\d{4}$/', $date)) {
    return;
  }

  // Split the date into day, month, and year.
  list($day, $month, $year) = explode('-', $date);

  // If the month name is capitalized properly, we can exit this function.
  if (preg_match('/^[A-Z][a-z]{2}$/', $month)) {
    return;
  }

  // Otherwise, we need to ensure than the first letter is in uppercase while
  // the remaining two letters are in lowercase. Note that the date may still be
  // invalid, but date_popup_validate() will handle proper date validation.
  $month = drupal_ucfirst(drupal_strtolower($month));

  // Put the date back together with the modified month.
  $date = $day . '-' . $month . '-' . $year;

  // Set the actual value that will be used in date_popup_validate().
  form_set_value($element, array('date' => $date, 'time' => ''), $form_state);

  // Setting this will cause the updated value to be displayed when the form
  // is rendered after being submitted without any errors.
  $form_state['input'][$element['#name']]['date'] = $date;

  // Setting this will cause the updated value to be displayed when the form
  // is rendered after being submitted with errors.
  $form_state['complete form'][$element['#name']]['date']['#value'] = $date;

  // Setting these doesn't seem to have any effect, but for the sake of
  // completeness, we might as well overwrite the old value everywhere.
  $form_state['complete form'][$element['#name']]['#value']['date'] = $date;
  $form_state['complete form'][$element['#name']]['date']['#default_value'] = $date;
}
anpolimus’s picture

Issue tags: +Need tests

This task needs test first.

anpolimus’s picture

Status: Needs review » Needs work
anpolimus’s picture

Assigned: Unassigned » anpolimus