credit-card-type

repository·main·Indexed 21 days ago

https://github.com/braintree/credit-card-type

A utility library for identifying credit card brands from card numbers, supporting partial number detection for type-as-you-go functionality. It provides metadata including expected lengths, formatting gaps, and security code requirements. The library allows for extending or modifying supported card types via addCard, updateCard, removeCard, and changeOrder methods.

Tokens
3.4K
Snippets
17
Records
18
Agent score
77%

What's inside credit-card-type

  1. How pattern detection works

    main

    The library uses a patterns array for each card type to determine matches. Patterns can be:

    1. A Number: The card number must start with this number. Partial matches are supported (e.g., pattern 123 matches 1, 12, 123, and 1234).
    2. A Range (Array of 2 numbers): The card number must fall within the range [min, max]. Partial matches are supported (e.g., range [100, 123] matches 1, 10, 100, 12, 120, and 123).

    Priority Logic: If multiple card types match, the library prefers the one where the entirety of the pattern is matched. For example, if a number matches both a generic Visa pattern (starts with 4) and a specific Elo pattern (starts with 401178), the library will report only Elo once the number reaches the full length of the Elo pattern.

  2. Import credit-card-type in CommonJS and ES6

    main

    The library supports both CommonJS and ES6 module syntax.

    // CommonJS
    var creditCardType = require("credit-card-type");
    var getTypeInfo = require("credit-card-type").getTypeInfo;
    var CardType = require("credit-card-type").types;
    
    // ES6
    import creditCardType, {
      getTypeInfo,
      types as CardType,
    } from "credit-card-type";
  3. Get information for a specific card type with getTypeInfo()

    main

    The creditCardType.getTypeInfo(type: String) method returns a single object containing the configuration (gaps, lengths, code, etc.) for the specified card type. It returns undefined if the provided type is invalid or unknown.

    var creditCardType = require("credit-card-type");
    var info = creditCardType.getTypeInfo("visa");
    // Returns the object for Visa
  4. Extend the library with addCard()

    main

    You can register new card brands or overwrite existing ones using creditCardType.addCard(config). New cards are added to the bottom of the priority list by default.

    Configuration Object:

    • niceType: String
    • type: String
    • patterns: Array of numbers or ranges (e.g., [123, [100, 123]])
    • gaps: Array of indices
    • lengths: Array of expected lengths
    • code: Object { name: String, size: Number }
    creditCardType.addCard({
      niceType: "NewCard",
      type: "new-card",
      patterns: [2345, 2376],
      gaps: [4, 8, 12],
      lengths: [16],
      code: {
        name: "CVV",
        size: 3,
      },
    });
  5. Update existing card types with updateCard()

    main

    Use creditCardType.updateCard(type, config) to modify properties of an existing card. Any properties omitted from the config object will be inherited from the original card definition.

    creditCardType.updateCard(creditCardType.types.VISA, {
      niceType: "Fancy Visa",
      lengths: [11, 16],
    });
  6. Use creditCardType() to detect card brands

    main

    The creditCardType(number: String) function takes a normalized card number string (containing only integers) and returns an array of objects representing potential card matches. This supports partial numbers for type-as-you-go detection.

    Each returned object contains:

    • niceType (String): A pretty-printed brand name (e.g., 'Visa').
    • type (String): A code-friendly brand name (e.g., 'visa').
    • gaps (Array): Expected indices for spaces in a formatted string.
    • lengths (Array): Expected lengths of the card number.
    • code (Object): Security code information (name and size).

    If no matches are found, it returns an empty array.

    var creditCardType = require("credit-card-type");
    
    // The card number should be normalized (integers only) prior to usage.
    var visaCards = creditCardType("4111");
    console.log(visaCards[0].type); // 'visa'
    
    var ambiguousCards = creditCardType("6");
    console.log(ambiguousCards.length); // 6
    console.log(ambiguousCards[0].niceType); // 'Discover'
  7. Manage card priority with changeOrder() and removeCard()

    main

    When adding custom cards, you can control their detection priority or remove existing ones.

    • changeOrder(type, index): Moves the specified card type to the provided index in the priority array. Lower indices have higher priority.
    • removeCard(type): Removes the specified card type from the library.
    • resetModifications(): Reverts all changes made via addCard, updateCard, removeCard, or changeOrder to the original state.
    // Move custom card to highest priority
    creditCardType.changeOrder("my-new-card", 0);
    
    // Remove a card
    creditCardType.removeCard(creditCardType.types.VISA);
    
    // Reset all changes
    creditCardType.resetModifications();
  8. Reference: Security Code (CVV/CVC) details by brand

    main

    The code object returned by the API provides the nomenclature and required length for the security code of each brand.

    Brand              | Name   | Size |
    -------------------|--------|------|
    Visa               | CVV    | 3    |
    Mastercard         | CVC    | 3    |
    American Express   | CID    | 4    |
    Diners Club       | CVV    | 3    |
    Discover           | CID    | 3    |
    JCB                | CVV    | 3    |
    UnionPay           | CVN    | 3    |
    Maestro            | CVC    | 3    |
    Mir                | CVP2 | 3    |
    Elo                | CVE    | 3    |
    Hiper              | CVC    | 3    |
    Hipercard          | CVC    | 4    |
    Verve              | CVV    | 3    |
    Naranja            | CVV    | 3    |
    Troy               | CVV    | 3    |
  9. Reference: Supported Card Type Constants

    main

    The library provides named constants for all supported card types to avoid string typos. These are available via the types property (or as a named export in ES6).

    AMERICAN_EXPRESS
    DINERS_CLUB
    DISCOVER
    ELO
    HIPERCARD
    HIPER
    JCB
    MAESTRO
    MASTERCARD
    MIR
    UNIONPAY
    VISA
    VERVE
    NARANJA
    TROY
  10. Manage custom card types with addCard(), removeCard(), and updateCard()

    main

    The library allows you to extend or modify the set of supported card types at runtime.

    • Add a card: creditCardType.addCard(config: CreditCardType) adds a new card configuration. If the type doesn't exist, it is appended to the end of the matching order.
    • Remove a card: creditCardType.removeCard(name: string) removes a card type from the matching order. Throws an error if the name is not supported.
    • Update a card: creditCardType.updateCard(cardType: string, updates: Partial<CreditCardType>) modifies an existing card's configuration. You cannot overwrite the type property via this method; use addCard for that.
    // Adding a custom card
    creditCardType.addCard({
      type: 'my-custom-card',
      patterns: [/1234/],
      // ... other CreditCardType properties
    });
    
    // Updating an existing card
    creditCardType.updateCard('visa', { patterns: [/new-pattern/] });
    
    // Removing a card
    creditCardType.removeCard('troy');
  11. Detect card types with creditCardType()

    main

    The primary function creditCardType(cardNumber: string) identifies the credit card brand(s) associated with a given card number.

    • If a single best match is found, it returns an array containing only that CreditCardType.
    • If no single best match is found, it returns an array of all matching CreditCardType objects.
    • If the input is invalid, it returns an empty array.
    • If an empty string is provided, it returns all available card types in the current test order.
    import creditCardType from 'credit-card-type';
    
    const matches = creditCardType('4111111111111111');
    console.log(matches);