Skip to content

Instantly share code, notes, and snippets.

@le717
Created July 11, 2018 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save le717/f8912665d59007daddc087e8a3ed0e83 to your computer and use it in GitHub Desktop.
Save le717/f8912665d59007daddc087e8a3ed0e83 to your computer and use it in GitHub Desktop.
<?php
function valid_cc_expire_format($val) {
return (bool) preg_match('/\d{2}\/\d{4}/', $val);
}
function valid_cc_expire_value($val) {
$currentMonth = intval(date('n'));
$currentYear = intval(date('Y'));
$r = preg_match('/(\d{2})\/(\d{4})/', $val, $matches);
// Could not match valid input
if (!$r) {
return false;
}
// Pull out the given month/year values for easier use
$givenMonth = intval($matches[1]);
$givenYear = intval($matches[2]);
// Make sure we are in a valid month/year range
// A valid year is defined as the current year or higher
// Be pessimistic and assume the card is expired by default
$isValidYear = $givenYear >= $currentYear;
$isValidMonth = false;
// Month-checking is a little more nuanced
// We can't have a past month in the current year
// but we _can_ have a month in a future year
if ($isValidYear) {
// The card expires this year, make sure the month hasn't passed
if ($givenYear === $currentYear) {
$isValidMonth = $givenMonth >= $currentMonth;
// If it's not the current year, then the card expires in the future
// In that case, all months are valid
} else {
$isValidMonth = true;
}
}
return $isValidMonth && $isValidYear;
}
function check_valid_cc_expire($val) {
return valid_cc_expire_format($val) && valid_cc_expire_value($val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment