Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match credit card expiration date

Tags:

regex

I have the following pattern which I'm trying to use to match credit card expiration dates:

(0[1-9]|1[0-2])\/?(([0-9]{4})|[0-9]{2}$)

and I'm testing on the following strings:

02/13
0213
022013
02/2013
02/203
02/2
02/20322

It should only match the first four strings, and the last 3 should not be a match as they are invalid. However the current pattern is also matching the last string. What am I doing wrong?

like image 514
Snowman Avatar asked Dec 06 '13 17:12

Snowman


People also ask

How do I know the expiration date of my credit card?

Expiration dates appear on the front or back of a credit card in a two-digit month/year format. Credit cards expire at the end of the month written on the card. For example, a credit card's expiration date may read as 11/24, which means the card is active through the last day of November 2024.

Is a credit card valid on the expiration date?

A credit card expiration date tells you when the card is no longer valid. After your card expires, you shouldn't be able to use it, because the issuers should deactivate the credit card when it reaches the expiration date.

What is RegEx in validation?

What is RegEx Validation (Regular Expression)? RegEx validation is essentially a syntax check which makes it possible to see whether an email address is spelled correctly, has no spaces, commas, and all the @s, dots and domain extensions are in the right place.


2 Answers

You're missing start of line anchor ^ and parenthesis are unmatched.

This should work:

re = /^(0[1-9]|1[0-2])\/?([0-9]{4}|[0-9]{2})$/;

OR using word boundaries:

re = /\b(0[1-9]|1[0-2])\/?([0-9]{4}|[0-9]{2})\b/;

Working Demo: http://regex101.com/r/gN5wH2

like image 84
anubhava Avatar answered Sep 18 '22 05:09

anubhava


Since we're talking about a credit card expiration date, once you have validated the input date string using one of the fine regex expressions in the other answers, you'll certainly want to confirm that the date is not in the past.

To do so:

  1. Express your input date string as YYYYMM. For example: 201409
  2. Do the same for the current date. For example: 201312
  3. Then simply compare the date strings lexicographically: For example: 201409 ge 201312.

In Perl, ge is the greater than or equal to string comparison operator. Note that as @Dan Cowell advised, credit cards typically expire on the last day of the expiry month, so it would be inappropriate to use the gt (greater than) operator.

Alternatively, if your language doesn't support comparing strings in this fashion, convert both strings to integers and instead do an arithmetic comparison.

like image 21
DavidRR Avatar answered Sep 18 '22 05:09

DavidRR