Skip to content

Instantly share code, notes, and snippets.

@LionC
Forked from gabrielbauman/CardType.java
Last active June 8, 2021 06:52
Show Gist options
  • Save LionC/a0fa374df1770b8a58ea6e1cb0a9c845 to your computer and use it in GitHub Desktop.
Save LionC/a0fa374df1770b8a58ea6e1cb0a9c845 to your computer and use it in GitHub Desktop.
A Java enum representing credit card types (Visa, Mastercard etc) that can detect card type from a credit card number.
package com.gabrielbauman.gist;
import java.util.regex.Pattern;
public enum CardType {
UNKNOWN,
VISA("^4[0-9]{12}(?:[0-9]{3})?$"),
MASTERCARD("^5[1-5][0-9]{14}$"),
AMERICAN_EXPRESS("^3[47][0-9]{13}$"),
DINERS_CLUB("^3(?:0[0-5]|[68][0-9])[0-9]{11}$"),
DISCOVER("^6(?:011|5[0-9]{2})[0-9]{12}$"),
JCB("^(?:2131|1800|35\\d{3})\\d{11}$"),
CHINA_UNION_PAY("^62[0-9]{14,17}$");
private Pattern pattern;
CardType() {
this.pattern = null;
}
CardType(String pattern) {
this.pattern = Pattern.compile(pattern);
}
public static CardType detect(String cardNumber) {
for (CardType cardType : CardType.values()) {
if (null == cardType.pattern) continue;
if (cardType.pattern.matcher(cardNumber).matches()) return cardType;
}
return UNKNOWN;
}
}
package com.gabrielbauman.gist;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CardTypeTest {
@Test
public void testDetection() {
assertEquals(CardType.VISA, CardType.detect("4000056655665556"));
assertEquals(CardType.VISA, CardType.detect("4242424242424242"));
assertEquals(CardType.MASTERCARD, CardType.detect("5105105105105100"));
assertEquals(CardType.MASTERCARD, CardType.detect("5200828282828210"));
assertEquals(CardType.MASTERCARD, CardType.detect("5555555555554444"));
assertEquals(CardType.AMERICAN_EXPRESS, CardType.detect("371449635398431"));
assertEquals(CardType.AMERICAN_EXPRESS, CardType.detect("378282246310005"));
assertEquals(CardType.DISCOVER, CardType.detect("6011000990139424"));
assertEquals(CardType.DISCOVER, CardType.detect("6011111111111117"));
assertEquals(CardType.DINERS_CLUB, CardType.detect("30569309025904"));
assertEquals(CardType.DINERS_CLUB, CardType.detect("38520000023237"));
assertEquals(CardType.JCB, CardType.detect("3530111333300000"));
assertEquals(CardType.JCB, CardType.detect("3566002020360505"));
assertEquals(CardType.CHINA_UNION_PAY, CardType.detect("6271862582187946"));
assertEquals(CardType.CHINA_UNION_PAY, CardType.detect("6211434804519679"));
assertEquals(CardType.UNKNOWN, CardType.detect("0000000000000000"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment