zen of coding

Self-adjusting credit card expiration year

Once in a while, it happens, that you need to build a payment form with credit card expiration year as a select input.

With CakePHP’s form helper it’s pretty easy, but what’s even nicer is that you don’t have to hard-code any values for the actual years (and then have to remember to update them as the time goes on).

With the little snippet below we build a select input which starts and defaults to the current year and goes up to seven years ahead.

(So at the time of writing the select input range is: 2010 – 2017)

$this->Form->input('card_expiration_year', array(
                           'type' => 'date',
                           'maxYear' => date('Y', strtotime('+ 7 years')),
                           'minYear' => date('Y'),
                           'dateFormat' => 'Y',
                           'default' => date('Y')));

p.s. Why seven years? (Not sure, just like the number).

  • Pingback: Tweets that mention Self-adjusting credit card expiration year | nuts and bolts of cakephp -- Topsy.com()

  • keymaster

    … but cake defaults the order to descending (Starting from 2017 down to 2010.

    If you want as ascending order of years in the dropdown, add an ‘orderYear’ key, and set it to ‘asc’, as follows (not mentioned in cookbook):

    echo $this->Form->input(‘OrderCreditCard.expiry_year’, array(
    ‘label’ => ‘Expiry Year’,
    ‘type’ => ‘date’,
    ‘maxYear’ => date(‘Y’),
    ‘minYear’ => date(‘Y’, strtotime(‘+ 7 years’)),
    ‘dateFormat’ => ‘Y’,
    ‘default’ => date(‘Y’),
    ‘orderYear’ => ‘asc’
    ));

  • teknoid

    @keymaster

    Thanks. C’mon now, copy and paste into cookbook ;)

    • keymaster

      done (in a comment).

  • teknoid

    @keymaster

    Thanks!

  • ajaxian

    how about the months and days??
    I need to validate an inicial date and a finish date for inscription web app.
    could anyone response me?
    Thanks

  • teknoid

    @ajaxian

    The validation is kind of unrelated.
    We usually have 12 months and most of the time can get away with a list of 31 days.

  • ajaxian

    thanks teknoid! seems I have to create my own validation rule, to compare between the initial and final date for the course, and of course initial <= final date.
    See you

%d bloggers like this: