regular expression to test 4 digit credit card expiry date in date format mmyy in javascript

To test a 4 digit credit card expiry date in the "MMYY" format using regular expressions in JavaScript, you can use the following regex pattern:

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

This pattern will match any two digits between 01-12 for the month (with a leading zero if necessary) and any two digits between 00-99 for the year.

Here's an example of how to use this regex pattern in a function:

index.tsx
function testExpiryDate(expiry) {
  const regex = /^(0[1-9]|1[0-2])([0-9]{2})$/;
  return regex.test(expiry);
}

// Example usage:
console.log(testExpiryDate("1221")); // true
console.log(testExpiryDate("1302")); // true
console.log(testExpiryDate("13/02")); // false
console.log(testExpiryDate("0213")); // false
console.log(testExpiryDate("130")); // false
359 chars
12 lines

Note that this pattern only tests the format of the expiry date and not its validity. To validate the expiry date, you may also need to check if it is not in the past or too far in the future based on your business requirements.

gistlibby LogSnag