I created a custom module for form which accepts from date and to date as user input i would like to restrict the user from selecting a date prior to current date. below is my code snippet.

$form['oneway']['from_date'] = array (
'#type' => 'date',
'#title' => t('From Date'),
'#date_year_range' => '-80:0',
'#required' => TRUE,
);

Please help me out ....

Thank & Regards,
Ramesh S

Comments

joshi.rohit100’s picture

Drupal 8 or 7 ?

rameshsomepalli99’s picture

Hi Joshi,

its drupal 8

joshi.rohit100’s picture

$form['oneway']['from_date'] = array (
        '#type' => 'date',
        '#title' => t('From Date'),
        '#date_year_range' => '-80:0',
        '#required' => TRUE,
        '#attributes' => [
            'min' =>  \Drupal::service('date.formatter')->format(REQUEST_TIME, 'custom', 'Y-m-d'),
        ],
    );
rameshsomepalli99’s picture

Hi Joshi,

Thank you so much. Works like a charm.

Thanks & Regards,
Ramesh S

vignesh226’s picture

Hi 
its working for me but i want 60 days restrict. Any suggestions please

revati_gawas’s picture

Hey
if you want to set previous 60 days  then just use

date('Y-m-d', strtotime('-60 days'))

 and for next 60 days just replace - with + 
e.g 

'#attributes' => [
  'min' => date('Y-m-d', strtotime('-60 days')),
  'max' => date('Y-m-d'),
],
Kumar Ashutosh’s picture

I used this in D8 but the output is not as expected.