Regex MM/YYYY Regular Expression for Credit Card Expiration Date
April 10th, 2009 | Published in technology, Web Development | 1 Comment
Here is a simple credit card expiration date regular expression. I wrote my own regexp for the expiration date since one was not easily found on the net. This one validates for allowing the year 2009 to 2029, but could be easily changed…I built this for an ASP.NET programming project for a course I’m taking.
1 | ^((0[1-9])|(1[0-2]))\/((2009)|(20[1-2][0-9]))$ |
This version just checks for 4 digits after the “/” character.
Above is the full reg ex. It validates a numeric 2 digit month, allowing only for 01-12. It also ensures that a “/” character is at position three.
Here is a step by step explanation of the code:
- ^((0[1-9]) – this says the first digit must be a 0 and the second digit can be 1 to 9. This gives a positive match for months 01,02,03,04,05,06,07,08,09
- | – this is the “or” character, which tells the regex to check for pattern A OR pattern b
- (1[0-2])) – This is the second part of the OR – it check for 1 in position 1, and a 0 to 2 in position 2. This gives a match for months 10,11,12
- \/ – this checks for the “/” in position three. The “\” character is the escape character, and just allows the “/” to exist there, since it’s really a special character.
- ((2009)| – this checks for a 2009 in positions 4 through 7 and then says “OR”…
- (20[1-2][0-9]))$ – this is the “OR” branch. It checks for a 2 and 0 in positions 4 and 5, for the “two thousand and…”, then it checks for a digit 1-2 in position 6, to match 201* and 202*. The [0-9] portion says that the final digit in position seven can be anything from 0 to 9. This branch of the reg ex matches any year from 2010 to 2029. Of course you can tinker with it to accommodate years you wish to validate for.
Or if you don’t care what year is entered, you can use this:
1 | ^((0[1-9])|(1[0-2]))\/(\d{4})$ |
Subject Tags:
Regular Expression for cc expiration mm/yyyy
month/year regex
validate credit card exp date mm/yyyy
June 22nd, 2015 at 5:03 am (#)
Thanks for the share.
For some reason, your last piece of code which ignores specific years, doesn’t work in javascript.
This works for me, which is weird, it is suppose to do the same thing : replaced “d” with “[0-9]”
^((0[1-9])|(1[0-2]))/([0-9]{4})$