credit-card-type
Detect a credit card brand from a full or partial number.
credit-card-type figures out the card brand (Visa, Mastercard, American Express, …) from
a card number — including partial numbers, for type-as-you-go detection as the user
types. It is not a validation library; it is the building block a payment form uses to
show the right brand icon, apply the right spacing, and hint the CVV length.
A faithful Rust port of Braintree's
credit-card-type npm package, which has
no Rust equivalent.
- Zero dependencies
#![no_std]- 14 brands: Visa, Mastercard, American Express, Diners Club, Discover, JCB, UnionPay, Maestro, Mir, Elo, Hiper, Hipercard, Verve, Naranja
- Differential-tested against the reference
credit-card-typeimplementation
Install
[]
= "0.1"
Usage
use credit_card_type;
// A long-enough prefix resolves to a single brand.
let cards = credit_card_type;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!; // "4111 1111 1111 1111"
assert_eq!;
assert_eq!;
assert_eq!;
// A short, ambiguous prefix returns every candidate (good for live UI feedback).
let ambiguous = credit_card_type;
assert!; // Discover, UnionPay, Maestro, Elo, Hiper, Hipercard
// An impossible prefix returns nothing; an empty string returns all brands.
assert!;
assert_eq!;
Look up a brand's metadata directly:
use ;
let amex = get_type_info.unwrap;
assert_eq!; // "3782 822463 10005"
assert_eq!;
assert_eq!;
assert_eq!;
Returned data
credit_card_type returns a Vec<CardType>, each with:
| Field | Meaning |
|---|---|
type_ |
code-friendly id, e.g. visa, american-express |
nice_type |
display name, e.g. Visa, American Express |
gaps |
indices to insert spaces when formatting (e.g. [4, 8, 12]) |
lengths |
valid total digit lengths |
code |
security-code name and size |
match_strength |
Some(n) once the input is determinate, used to pick the best match |
When the input is long enough to identify one brand conclusively, the result has a single entry; otherwise every still-possible brand is returned in a stable order.
Normalize first: strip spaces and separators so the input is digits only.
Note on scope
This port covers detection (credit_card_type and get_type_info). The npm package's
runtime customization API (addCard / updateCard / removeCard / changeOrder), which
relies on mutable global state, is intentionally omitted.
Contributors ✨
This project follows the all-contributors specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the emoji key for how each contribution is recognized, and open a PR or issue to get involved.
Thanks goes to these wonderful people:
License
Licensed under either of MIT or Apache-2.0 at your option.