create a regex to validate a credit card expiry field in format mm-yy in javascript

You can use the following regex to validate a credit card expiry field in format mm-yy in JavaScript.

index.tsx
const regex = /^(0[1-9]|1[0-2])\-(\d{2})$/;
const isValid = regex.test("02-23"); // change "02-23" to your desired input
console.log(isValid); // true if the input is valid
173 chars
4 lines

In this regex, ^(0[1-9]|1[0-2]) matches the month part of the input, ensuring that it's a valid month number between 01 and 12. \- matches the hyphen separator, and (\d{2})$ matches the year part of the input, ensuring that it's a valid 2-digit number.

Note that the year range will only match from 00-99. If you want year range from 00-50. You can use this modified regex /^(0[1-9]|1[0-2])-(20|2[1-5]|[3-4]\d|5[0])$/.

related categories

gistlibby LogSnag