regex to test if a credit card expiry date entered in format mmyy is valid or not in javascript

Here is an example regex to validate if a credit card expiry date is in the format mmyy and is valid:

index.tsx
function validateExpiryDate(date) {
  const regex = /^(0[1-9]|1[0-2])\/?([0-9]{2})$/;
  if (regex.test(date)) {
    const expiryMonth = parseInt(date.slice(0, 2), 10);
    const expiryYear = parseInt(date.slice(2), 10);
    const currentMonth = new Date().getMonth() + 1;
    const currentYear = parseInt(new Date().getFullYear().toString().slice(2), 10);
    if (expiryYear > currentYear || (expiryYear === currentYear && expiryMonth >= currentMonth)) {
      return true;
    }
  }
  return false;
}
502 chars
14 lines

Explanation:

  • The regex pattern ^(0[1-9]|1[0-2])\/?([0-9]{2})$ matches strings that start (^) with a valid month number (01 - 12) in the format m/ or mm/ (with or without a slash), followed by a two-digit year number within the range of 00 to 99 ($).
  • The function then extracts the month and year from the string, compares it with the current month and year, and returns true if the expiry date is valid.

gistlibby LogSnag