Test the candidate set before choosing a brand

A complete number can match a broad fallback and a specific rule at the same time. An incomplete number has another complication: its strongest possible match may need more digits. This guide replaces a first-match regex chain with a resolver that makes both situations visible.

The resolver is the implementation used by the number validator and prefix analyser. Its input is a normalized digit string; a brand result is local to the supplied profile, not proof of issuer allocation or payment acceptance.

The configured patterns

NetworkConfigured prefixesLengths
American Express34, 3715
Diners Club300–305, 36, 38, 3914, 16, 19
Discover6011, 65, 644–64916, 19
JCB3528–358916, 17, 18, 19
Maestro50, 56–69 (broad fallback)12, 13, 14, 15, 16, 17, 18, 19
Mastercard51–55, 2221–272016
Troy979216
UnionPay62, 8116, 17, 18, 19
Visa413, 16, 19

This table is rendered from the same JSON profile passed to the tools. Its Maestro range is explicitly a broad fallback; it is not a claim that every number in that interval is Maestro. Its Troy, JCB and Discover entries are limited test profiles, not exhaustive lists of every legacy or co-badged product. See the length comparison for the generator’s narrower scope.

Braintree’s pattern-detection documentation describes partial matching and preference for a stronger pattern. The implementation here is our own small resolver, with an explicit unresolved state for equally specific conflicts.

A prefix regex does not decide the whole input state

For a completed prefix, Mastercard’s configured four-digit interval is 2221–2720. A shortcut such as ^2[2-7] also includes 2200 and 2799, which are outside that interval. The Mastercard boundary fixtures supply focused comparisons.

Typing behavior needs a different test. 6 is compatible with multiple rules, and 60 must leave 6011 possible. Even though the broad Maestro fallback matches once enough digits are present, it must not conceal that unfinished, more specific Discover pattern.

Typed inputSelected brand in this profileReason
6NoneMultiple patterns remain possible
60NoneMore specific 6011 is still unfinished
6011DiscoverThe stronger pattern is complete
62UnionPayExact prefix outranks the wider two-digit fallback
35, then 353NoneThis profile waits for four JCB prefix digits
3530JCBFour-digit interval match is complete

The JCB typing exercise tests later input states. A selected prefix still does not mean the entire number is long enough or has a passing checksum.

Inspect the resolver

Patterns are either digit strings or equal-width inclusive intervals. The code compares only the short prefix as a number; it never converts the complete PAN to a JavaScript number. More digits mean greater specificity. At the same width, a narrower interval wins.

function patternMatch(digits, pattern) {
  const from = typeof pattern === 'string' ? pattern : String(pattern.from);
  const to = typeof pattern === 'string' ? pattern : String(pattern.to);
  const prefix = digits.slice(0, from.length);
  const low = Number(prefix.padEnd(from.length, '0'));
  const high = Number(prefix.padEnd(from.length, '9'));
  if (high < Number(from) || low > Number(to)) return null;
  return { width: from.length, span: Number(to) - Number(from), complete: digits.length >= from.length };
}

export function prefixCandidates(digits, profile) {
  if (typeof digits !== 'string' || !digits || /[^0-9]/.test(digits)) {
    return { state: 'incomplete', brand: null, candidates: [] };
  }
  const matches = Object.entries(profile.networks).flatMap(([brand, rule]) =>
    rule.prefixes.flatMap(pattern => {
      const match = patternMatch(digits, pattern);
      return match ? [{ brand, ...match }] : [];
    }));
  const candidates = [...new Set(matches.map(match => match.brand))].sort();
  if (!matches.length) return { state: 'unknown', brand: null, candidates };
  // Rank complete AND pending patterns. A broad match must not hide a possible
  // more specific brand while someone is still typing.
  matches.sort((a, b) => b.width - a.width || a.span - b.span);
  const best = matches[0];
  const strongest = matches.filter(m => m.width === best.width && m.span === best.span);
  const winners = [...new Set(strongest.map(match => match.brand))];
  if (strongest.some(match => !match.complete)) return { state: 'incomplete', brand: null, candidates };
  if (winners.length !== 1) return { state: 'ambiguous', brand: null, candidates };
  return { state: 'matched', brand: winners[0], candidates };
}

Pending patterns participate in ranking, so a broad complete match cannot win while a stronger possible match remains unfinished. Equal-strength winners with different brand names return ambiguous. The full candidate list is retained to explain the result.

Run cases that a happy-path test misses

Extract the shared test bundle and run:

node --test card-validation.test.mjs

The assertions cover prefix boundaries, incomplete values, unknown prefixes, a reversed rule order and a deliberately conflicting rule. They also verify that every configured generator prefix endpoint and output length is recognized by the validation profile. The Maestro comparison exercise isolates overlapping rules with a smaller configuration when you need to debug that behavior on its own.

Keep routing and validation separate

Do not turn unknown into “this account does not exist,” or matched into “this merchant accepts it.” The BIN/IIN reference explains what requires maintained data. A provider response or merchant configuration answers a different question from the prefix resolver.

Likewise, normalize only the separators your input contract permits. Removing every non-digit character would turn a malformed value into a different value before matching. The shared code guide documents that contract and tests it across four languages.

Frequently Asked Questions

Why not use a chain of first-match regexes?
A broad pattern can win before a more specific one, and partial input may still grow into another brand. The example tracks pending matches and resolves complete patterns by specificity.
Does a single 6 identify Maestro?
No. This profile still has Discover, Maestro and UnionPay candidates at that point. Its resolver returns no selected brand until the stronger matching pattern is complete.
What happens when equally specific rules name different brands?
The result is ambiguous with no selected brand. The test suite adds such a conflicting rule deliberately, rather than allowing array order to choose an answer.
Are these rules a complete production routing table?
No. They are this site’s versioned test profile. Use maintained provider data for acceptance and routing, and keep that decision separate from local display candidates.