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.tsx49 chars2 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 stringExample usage:
index.tsx421 chars11 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