reg ex to validate credit card expiry date with months represented by two digits from 01 to 12 and years in two digits from current year up to 2099 in javascript

Here's a regular expression to validate the credit card expiry date in the format MM/YY or MM/YYYY:

index.tsx
function validateExpiryDate(expiryDate) {
  const regex = /^(0[1-9]|1[0-2])\/(2[1-9]|[3-9][0-9])$/;
  const currentYear = new Date().getFullYear().toString().substr(-2);
  const matches = expiryDate.match(regex);
  if (!matches) {
    return false;
  }
  const [, expiryMonth, expiryYear] = matches;
  if (expiryYear.length === 2) {
    expiryYear = parseInt(`20${expiryYear}`);
  } else {
    expiryYear = parseInt(expiryYear);
  }
  if (expiryYear < currentYear || expiryYear > 99 + currentYear) {
    return false;
  }
  return true;
}
539 chars
19 lines

The regular expression ^(0[1-9]|1[0-2])\/(2[1-9]|[3-9][0-9])$ matches strings that start with either 01-12 followed by a forward slash /, and then followed by 21-99 or 3-9 plus any single digit.

The validateExpiryDate function also checks whether the expiry year is between the current year and 2099, and returns a boolean value indicating whether the date is valid.

gistlibby LogSnag