Skip to content

Instantly share code, notes, and snippets.

@tangentlin
Created March 31, 2024 01:27
Show Gist options
  • Save tangentlin/75a6b7017ac5fbc78eb5a8d4d6b020ff to your computer and use it in GitHub Desktop.
Save tangentlin/75a6b7017ac5fbc78eb5a8d4d6b020ff to your computer and use it in GitHub Desktop.
interface CreditCardType {
name: string;
logoUri: string;
validate: (number: string) => boolean;
format: (number: string) => string;
}
const creditCardTypes: Record<string, CreditCardType> = {
visa: {
name: "Visa",
logoUri: "/logos/visa.png",
validate: (number) => /^4[0-9]{12}(?:[0-9]{3})?$/.test(number),
format: (number) => number.replace(/(\d{4})(?=\d)/g, "$1 "),
},
mastercard: {
name: "MasterCard",
logoUri: "/logos/mastercard.png",
validate: (number) => /^5[1-5][0-9]{14}$/.test(number),
format: (number) => number.replace(/(\d{4})(?=\d)/g, "$1 "),
},
discover: {
name: "Discover",
logoUri: "/logos/discover.png",
validate: (number) => /^6(?:011|5[0-9]{2})[0-9]{12}$/.test(number),
format: (number) => number.replace(/(\d{4})(?=\d)/g, "$1 "),
},
american_express: {
name: "American Express",
logoUri: "/logos/american_express.png",
validate: (number) => /^3[47][0-9]{13}$/.test(number),
format: (number) => number.replace(/(\d{4})(?=\d{5})/g, "$1 ").replace(/(\d{6})/, "$1 "),
}
// Additional credit card types can be added here...
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment