Validating Credit Card Expiration Dates with Regular Expressions

Validating Credit Card Expiration Dates with Regular Expressions

I've been working with Authorize.Net lately and found myself needing a regular expression to validate that a user entered a credit card expiration date in the format YYYY-MM.

I usually just coast on over to http://regexlib.com and pick up the exact expression for my needs, but I was surprised to find that there's no expression that matches what I want - a first for the site. Luckily, this is a simple enough expression that I could write it myself.

To validate the date is in the correct format, I can use a simple expression like
([0-9]{4})-([0-9]{2})

This will ensure that my format matches 4 digits followed by a dash and then 2 more digits.


However, this will also accept years and months that aren't necessarily valid.
For instance, I can only have months ranging from 01 to 12, so I wouldn't want 2013-14.
I can change this with the expression:
([0-9]{4})-((0[1-9])|(1[0-2]))

Additionally, I only want future dates. So, I added in logic to support only years beginning with "20xx" and only allow from 12 to 99 for the last two digits of the year.
((20)(1([2-9])|([2-9])([0-9])))-((0[1-9])|(1[0-2]))



This assumes your application will never take credit cards that expire after the year 2099, so that nobody will plug in values like 5007-07. Authorize.Net takes care of validating that the expiration date is correct and that the credit card is not expired, but if you want to really stay on top of it, you can dynamically load the validation expression into a RegularExpressionValidator or whatever control you decide to use and tweak the (1([2-9])|([2-9])([0-9])) part based on the year. For instance, to only accept the year 2014 and beyond, you would use ((20)(1([4-9])|([2-9])([0-9])))-((0[1-9])|(1[0-2]))



Find this helpful? Share it with others:

Posted Thursday, September 13, 2012