Checkout Validation for UnionPay Cards: BINs, 19 Digits, and Missing CVVs
Most card-validation code was written with an implicit template in mind: 16 digits, a 3-digit CVV, a postal code, and a number that passes the Luhn check. That template fits most Visa and Mastercard traffic. It does not
Most card-validation code was written with an implicit template in mind: 16 digits, a 3-digit CVV, a postal code, and a number that passes the Luhn check. That template fits most Visa and Mastercard traffic. It does not fit UnionPay well. When the template is wrong, the failure is silent. The shopper sees "invalid card number," leaves, and your processor never logs an attempt you could investigate.
This article covers the client-side and server-side validation logic needed so valid UnionPay cards reach your processor. It also covers how to account for the weaker fraud signals those transactions can carry. For background on the network itself, see How China UnionPay Cards Work Online & What Merchants Should Expect.
The four assumptions that break
Before writing any code, list the assumptions your current form makes. In most legacy checkouts, four of them cause UnionPay rejections:
-
Fixed length. UnionPay card numbers typically run from 16 to 19 digits. A
maxlength="19"attribute that counts spaces, or a regex like^\d{16}$, rejects valid cards. -
Brand detection by first digit. UnionPay numbers typically start with
62or81. Detection code that maps only4,5,3, and6can mislabel these numbers or drop them into a reject branch. - CVV is always present. Some UnionPay cards have no card verification value. If the form requires the field, the shopper cannot complete it.
- Postal code is always meaningful. Shoppers outside the US, UK, and Canada often have no postal code that address verification can check. A required ZIP field blocks them or invites junk input.
A possible fifth: some processors have documented that certain UnionPay numbers do not pass the Luhn checksum. Do not treat that as a universal rule. Check your processor's current documentation, because it determines whether a Luhn failure on a 62 number should block submission.
Data flow: where validation actually happens
The flow is easier to reason about when you separate it into stages:
[Input field] -> normalize -> detect brand -> client checks -> tokenize (processor JS/SDK)
-> your server -> processor -> network route (e.g., Discover in the US) -> issuer
The key point is that your code should block only inputs that are definitely invalid. Brand-specific rules beyond length and character checks belong to the processor and the issuer. Each extra rule you enforce is a chance to reject a card the network would have approved.
If you use a processor's hosted fields or tokenization library, most of this is handled for you. You still need to audit your own wrapper code. Custom formatting, analytics hooks, and "helpful" pre-submit checks often reintroduce the bugs.
Step-by-step implementation
Step 1: Normalize before anything else
Strip spaces and dashes, then confirm that only digits remain. Run every length check against the normalized string, not the raw input.
function normalizePan(raw: string): string | null {
const digits = raw.replace(/[\s-]/g, "");
return /^\d+$/.test(digits) ? digits : null;
}
If your input applies display formatting, set the HTML maxlength to the formatted length. For 19 digits grouped as 4-4-4-4-3, that is 23 characters with spaces. Don't set it to 19.
Step 2: Detect brand with ordered prefix ranges
Use a range table and match the longest prefix first. The overlap matters here: the BIN range 622126–622925 is allocated to Discover, and UnionPay can also issue cards in it. A detector that checks 62 before the narrower range, or the other way round with no clear intent, gives inconsistent labels.
type Brand = "unionpay" | "discover" | "visa" | "mastercard" | "unknown";
interface BrandRule {
brand: Brand;
from: number; // inclusive prefix start
to: number; // inclusive prefix end
prefixLen: number;
lengths: number[];
}
const RULES: BrandRule[] = [
// Discover/UnionPay overlap: label it, but accept either outcome downstream
{ brand: "discover", from: 622126, to: 622925, prefixLen: 6, lengths: [16,17,18,19] },
{ brand: "unionpay", from: 62, to: 62, prefixLen: 2, lengths: [16,17,18,19] },
{ brand: "unionpay", from: 81, to: 81, prefixLen: 2, lengths: [16,17,18,19] },
{ brand: "visa", from: 4, to: 4, prefixLen: 1, lengths: [13,16,19] },
// ...other brands
];
function detectBrand(pan: string): BrandRule | null {
const sorted = [...RULES].sort((a, b) => b.prefixLen - a.prefixLen);
for (const r of sorted) {
if (pan.length < r.prefixLen) continue;
const p = Number(pan.slice(0, r.prefixLen));
if (p >= r.from && p <= r.to) return r;
}
return null;
}
The brand label should drive UI hints only: the logo, the CVV field's visibility, and grouping. It should not be the reason a card is rejected. An unknown brand with a plausible length should still go to tokenization. The processor knows the current BIN tables, and your hard-coded list will drift out of date.
Step 3: Apply Luhn as a soft check for UnionPay
function luhnValid(pan: string): boolean {
let sum = 0;
let double = false;
for (let i = pan.length - 1; i >= 0; i--) {
let d = pan.charCodeAt(i) - 48;
if (double) { d *= 2; if (d > 9) d -= 9; }
sum += d;
double = !double;
}
return sum % 10 === 0;
}
function clientVerdict(pan: string): "block" | "warn" | "allow" {
const rule = detectBrand(pan);
if (pan.length < 12 || pan.length > 19) return "block";
if (rule && !rule.lengths.includes(pan.length)) return "warn";
if (!luhnValid(pan)) {
return rule?.brand === "unionpay" ? "warn" : "block";
}
return "allow";
}
warn means the form shows an inline hint ("Please double-check your card number") but still lets the shopper submit. Use a hard block only for lengths no card brand uses.
Step 4: Make CVV and postal code conditional
On the client, keep the CVV field visible but optional when the detected brand is UnionPay. Add a short hint such as "Leave blank if your card has no security code."
On the server, two changes are required:
- Your request schema must accept a missing CVC for these cards. Many teams relax the frontend and forget that a backend validator such as
cvc: z.string().length(3)still rejects the request. - Your processor's CVC and AVS rules must not auto-decline when the result is
unavailableornot checked. Check whether your risk rules treat "no result" the same as "mismatch."
Ask for a postal code only when the billing country uses one.
Decision table
| Condition | Client action | Server action |
|---|---|---|
| Length outside 12–19 after normalization | Block | Reject |
Prefix 62/81, length 16–19, Luhn passes |
Allow | Forward |
Prefix 62/81, Luhn fails |
Warn, allow submit | Forward; let processor decide |
Prefix 622126–622925
|
Allow; show either logo | Forward; don't assert brand |
| UnionPay, CVV empty | Allow | Accept null CVC; don't auto-decline on "unavailable" |
| Unknown prefix, plausible length, Luhn passes | Allow | Forward |
Compensating for weaker fraud signals
Accepting cards with no CVV and no AVS means you lose two checks that many rule sets depend on. Don't respond by blocking UnionPay outright. Move the weight to signals you still have:
- 3-D Secure. Request authentication on UnionPay transactions where your processor supports it. For card-not-present payments, authentication is what shifts fraud liability. Treat an authenticated result as the primary trust signal.
- Device and behavior data. Device fingerprint, account age, velocity of attempts per device, and shipping-address reuse work regardless of card brand.
-
Funding type. Many UnionPay cards are debit. If your processor returns a funding field (
debit/credit/prepaid), store it. You will need it in the next section.
Write rules in terms of signal availability, for example "CVC result unavailable AND not 3DS-authenticated AND new device." Avoid rules like "brand == unionpay." Rules keyed to availability also hold up when other brands send incomplete data.
Recurring billing: check before you store
UnionPay International's product documentation lists recurring transactions and pre-authorization for credit and signature-based debit cards, but not for PIN-based debit cards. For subscription products, that leads to a concrete failure mode. The first charge succeeds, the card is saved, and the first renewal fails.
Mitigations:
- Record funding type and brand when the card is saved.
- If your processor exposes it, check whether the card supports merchant-initiated transactions before you mark the subscription as auto-renewing.
- Route renewal failures for these cards to a dunning flow that asks the customer to authorize payment, rather than retrying silently.
Common mistakes and how to catch them
-
Formatted
maxlengthtoo short. Catch it with an E2E test that types a 19-digit number and checks the field value. - Backend schema stricter than frontend. Catch it with a contract test that posts a tokenized payment with no CVC.
- Analytics hooks that validate. Some form-tracking scripts flag "invalid" fields and block submission. Search your bundle for duplicated Luhn or regex logic.
-
Hard-coded BIN tables going stale. Log every
unknownbrand detection that still authorizes successfully. A rising count means your table needs updating. - Risk rules treating "unavailable" as "fail." Pull declines for UnionPay-detected cards and group them by CVC and AVS result code.
Test matrix
Use your processor's published UnionPay test numbers, not numbers you construct yourself. Cover at least:
| Case | Expected |
|---|---|
| 16-digit UnionPay, CVV present | Authorizes |
| 19-digit UnionPay | Field accepts all digits; authorizes |
| UnionPay, CVV omitted | Submits; no client or server validation error |
| Number in Discover overlap range | Accepted regardless of displayed logo |
| Non-US billing, no postal code | Submits |
| Saved UnionPay debit card, renewal | Handled by MIT check or dunning path |
If every row passes, your checkout no longer depends on the 16-digit, 3-digit-CVV template. UnionPay shoppers will reach your processor, and the decline decisions will come from the network and issuer instead of your form code.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.