basics · 2025-03-17 · 6 min read
Formatting card numbers as the user types — without breaking the caret
Grouping digits 4-4-4-4 (or 4-6-5 for Amex) cuts typos dramatically — if you do it without wrecking cursor position, paste or password-manager autofill.

Users read numbers in the groups printed on the card, so mirror that grouping in the input. Visa and Mastercard use 4-4-4-4; American Express uses 4-6-5; 14-digit Diners Club uses 4-6-4. The grouping has to switch live as the detected brand changes — type 37 then 42 in the inspection bench and watch the spacing adapt.
State vs. display
Keep the stored value digits-only and derive the formatted string for display. Validation, Luhn checks and tokenization all operate on the raw digits; only the input shows spaces.
Preserving the caret
Re-setting an input's value moves the cursor to the end, which makes editing in the middle impossible. Before formatting, count how many digits sit left of the caret; after formatting, place the caret after that many digits. Handle the end-of-string case separately so appending stays snappy.
Mobile keyboards and autofill
inputmode="numeric"opens the number pad on phones without forcingtype="number"(which strips leading zeros and breaks grouping) — see MDN on inputmode.autocomplete="cc-number",cc-name,cc-exp,cc-csclet browsers and password managers fill the whole form in one tap.- Strip non-digits on paste so '4242-4242-4242-4242' or numbers with spaces work.
- Set
maxlengthto 23 (19 digits + 4 separators), not 16.
Google's payment form best practices cover the full checklist. Pair good formatting with helpful error messages for the biggest conversion win.

Keywords: card number input, format credit card input, digit grouping, caret position, inputmode numeric, autocomplete cc-number, payment form UX
Frequently asked questions
Should a card number field use type=number?
No. Use type=text with inputmode=numeric; type=number strips leading zeros and prevents grouping with spaces.
How are Amex numbers grouped?
4-6-5 (e.g. 3782 822463 10005), unlike the 4-4-4-4 pattern of Visa and Mastercard.