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 99 in javascript

Here is a regular expression that validates credit card expiry date in the format MM/YY, with months represented by two digits from 01 to 12 and years in two digits from current year up to 99 in JavaScript.

index.tsx
const regex = /^(0[1-9]|1[0-2])\/([2-9][1-9])$/;
49 chars
2 lines

Explanation:

  • ^ indicates the beginning of the string
  • (0[1-9]|1[0-2]) matches any 2-digit month from 01 to 12
  • \/ matches the forward slash character
  • ([2-9][1-9])$ matches any two-digit year from current year (i.e. 21) up to 99
  • $ indicates the end of the string

Example usage:

index.tsx
const isValidExpiryDate = (expiryDate) => {
  const currentYear = String(new Date().getFullYear()).slice(-2);
  const regex = new RegExp(`^(0[1-9]|1[0-2])\\/${currentYear}[2-9][0-9]$`);
  return regex.test(expiryDate);
};

console.log(isValidExpiryDate('12/22')); // true
console.log(isValidExpiryDate('05/25')); // true
console.log(isValidExpiryDate('13/25')); // false
console.log(isValidExpiryDate('06/21')); // false
421 chars
11 lines

Here, the currentYear is first calculated using the getFullYear() method and then converted to a 2-digit string using slice(). We then construct a new regular expression using the RegExp constructor and the currentYear variable, to match against the expiry date input. The test() method is used to check if the input matches the regular expression and returns a boolean value accordingly.

gistlibby LogSnag