How to change the date year range on a Form API 'date' element

By default, the range of a date element goes from the year 1900 to 2050. In some cases, we don't want users to enter a year value in the future, so we're going to have to limit the range. Click 'read more' to find out how to change the year range. By default, the range of a date element goes from the year 1900 to 2050. In some cases, we don't want users to enter a year value in the future, so we're going to have to limit the range.

1) Add the '#process' property to your date Form API element, and add a property for the start and end year (or you could hardcode this later if you don't want to make it variable)

<?php
$form['date_of_birth'] = array(
  '#type' => 'date', 
  '#title' => t('Date of birth'), 
  '#process' => array('custom_date_element'), // ADD #process property 
  '#start_year' => 1900, 
  '#end_year' => format_date(time(), 'custom', 'Y'), 
); 
?>

2) Open the file /includes/form.inc and find the function expand_date().

3) Copy the function, and paste it in your own module. Change the name of the function to the value of your #process property (in our case custom_date_element)

4) Find the following code in the function:

5) Replace it by:

<?php
function custom_date_element($element) {
  (...)
  case 'year':
    $start_year = isset($element['#start_year']) ? $element['#start_year'] : 1900;
    $end_year = isset($element['#end_year']) ? $element['#end_year'] : format_date(time(), 'custom', 'Y');
    $options = drupal_map_assoc(range($start_year, $end_year));
    break;
?>

6) Now your form element should be within the range you supplied. Alternately you could also not use the #start_year and #end_year properties, but just change the range in your copied function, if you don't want to make them variable.