Linked-Field Payment Card Form with Live Validation
StringsModel answerLast updated
Build a browser payment card form where the detected card network drives number formatting, length checks and security-code rules, with validation and a submit callback.
Build a payment card form that runs in the browser. It has four inputs, and they depend on one another: what the user enters in one field changes how another field is formatted or checked.
Fields
- Card number
- Name on card
- Expiry date, written
MM/YY - Security code (CVC)
Required behavior
- As the user types the card number, detect the card network and display it.
- The detected network changes how the other fields behave (for example, the number's grouping and maximum length, and the allowed CVC length).
- Every field is validated. The submit button passes the values to a callback only when all fields are valid. No real payment call is made.
Constraints
- Plain JavaScript or any framework, but no form or validation libraries.
What to cover
Before coding, state your assumptions about these open points: which networks you support and what happens with an unknown one, when errors appear (keystroke, blur, or submit), whether the number is shown in groups, whether focus auto-advances, and what accessibility and autofill support you provide. Then describe your design and implement it.
Hints
Hint 1
Keep one state object (raw values plus a touched flag per field) and derive the network, formatted text and errors from it, instead of storing them separately.
Hint 2
Make a small table of network rules (prefix test, valid lengths, group boundaries, CVC length). Number formatting, the length check and the CVC check all read from the detected network.
Hint 3
For caret-safe formatting, count the digits to the left of the caret before reformatting, then put the caret after the same count of digits in the new string.
Hint 4
When the network changes, re-run validation for the CVC and the number, not just the field being edited. Show errors after blur or submit, and update them live once shown.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions to state first
- Networks: Visa, Mastercard, American Express and Discover. Anything else is "unknown" and gets generic rules: 12-19 digits, Luhn check, 3-4 digit CVC. I would not block unknown cards outright.
- Errors appear on blur or submit. After a field has shown an error, it re-validates on every keystroke so the message clears as soon as the input is fixed.
- The number is displayed in groups (4-4-4-4, or 4-6-5 for Amex).
- Focus auto-advances only when a field is complete and valid. This is optional and must not trap keyboard users.
State design
Keep a single source of truth: the raw values and a touched flag per field. Everything else is derived on each render.
const state = {
values: { number: '', name: '', expiry: '', cvc: '' },
touched: { number: false, name: false, expiry: false, cvc: false },
};
const network = () => detect(digitsOf(state.values.number));
const errors = () => validateAll(state.values, network());
Storing the network or the errors as separate state invites them going stale. Deriving them guarantees the linked behavior: when the number changes, the CVC error is recomputed automatically.
Network table
const NETWORKS = [
{ id: 'amex', test: /^3[47]/, lengths: [15], gaps: [4, 10], cvc: [4] },
{ id: 'visa', test: /^4/, lengths: [13, 16, 19], gaps: [4, 8, 12], cvc: [3] },
{ id: 'mastercard', test: /^(5[1-5]|2[2-7])/, lengths: [16], gaps: [4, 8, 12], cvc: [3] },
{ id: 'discover', test: /^(6011|65|64[4-9])/, lengths: [16], gaps: [4, 8, 12], cvc: [3] },
];
const UNKNOWN = { id: 'unknown', lengths: [12,13,14,15,16,17,18,19], gaps: [4, 8, 12, 16], cvc: [3, 4] };
const digitsOf = s => s.replace(/\D/g, '');
const detect = d => NETWORKS.find(n => n.test.test(d)) ?? UNKNOWN;
The Mastercard 2-series range (2221-2720) is simplified here. In an answer, say so and note that a numeric range check on the first four digits is the exact version.
Validation rules
- Number: digits only, length in
network.lengths, and a Luhn checksum pass. - Name: trimmed, non-empty. Do not restrict to ASCII letters, since real names contain accents, hyphens and apostrophes.
- Expiry: matches
MM/YY, month 1-12, and not in the past. A card is valid through the last day of its expiry month, so compare against the start of the following month. Optionally reject dates more than about 20 years out. - CVC: digits only, length in
network.cvc(4 for Amex, 3 otherwise).
function luhn(d) {
let sum = 0;
for (let i = 0; i < d.length; i++) {
let n = +d[d.length - 1 - i];
if (i % 2 === 1) { n *= 2; if (n > 9) n -= 9; }
sum += n;
}
return d.length > 0 && sum % 10 === 0;
}
function validateExpiry(v, now = new Date()) {
const m = /^(\d{2})\/(\d{2})$/.exec(v);
if (!m) return 'Use MM/YY';
const month = +m[1], year = 2000 + +m[2];
if (month < 1 || month > 12) return 'Invalid month';
if (new Date(year, month, 1) <= now) return 'Card has expired'; // valid through end of month
return '';
}
function validateAll(v, net) {
const d = digitsOf(v.number);
return {
number: !net.lengths.includes(d.length) ? 'Wrong number length'
: !luhn(d) ? 'Check the card number' : '',
name: v.name.trim() ? '' : 'Enter the name on the card',
expiry: validateExpiry(v.expiry),
cvc: net.cvc.includes(digitsOf(v.cvc).length) ? '' : `Enter ${net.cvc.join(' or ')} digits`,
};
}
Caret-safe formatting
Reassigning input.value moves the caret to the end, which breaks editing in the middle of the number. The fix: count the digits left of the caret before formatting, then restore the caret after the same count of digits.
function format(d, net) {
let out = '', prev = 0;
for (const g of net.gaps) if (d.length > g) { out += d.slice(prev, g) + ' '; prev = g; }
return out + d.slice(prev);
}
function onNumberInput(e) {
const el = e.target;
const before = digitsOf(el.value.slice(0, el.selectionStart)).length;
const maxLen = Math.max(...detect(digitsOf(el.value)).lengths);
const d = digitsOf(el.value).slice(0, maxLen); // also handles paste
const text = format(d, detect(d));
el.value = text;
let pos = 0, seen = 0;
while (pos < text.length && seen < before) if (/\d/.test(text[pos++])) seen++;
el.setSelectionRange(pos, pos);
state.values.number = text;
render();
}
Pasting works because all non-digits are stripped (spaces, dashes) before reformatting. For deletion, the caret logic handles backspace on a digit. For the expiry field, auto-inserting / has a classic bug: the user deletes the slash and the formatter puts it back. Handle it by checking inputType === 'deleteContentBackward' and dropping the preceding digit as well when the slash is removed.
Error timing and submit
- Mark a field
touchedon blur; show its error only iftouched. - On submit, mark all fields touched, compute errors, and if any exist, focus the first invalid field. Otherwise call
onSubmit(values). - When the network changes, the CVC error is recomputed from derived state. If the CVC is already touched, its message updates immediately (for example, switching to Amex now requires 4 digits).
Accessibility and autofill
- Real
<label>elements bound to inputs; no placeholder-only labels. - Error text in an element referenced by
aria-describedby, witharia-invalid="true"on the input, and anaria-live="polite"region for the network name. - Autofill attributes:
autocomplete="cc-number",cc-name,cc-exp,cc-csc. Useinputmode="numeric"andtype="text"(nottype="number", which strips spaces and breaks the caret). - Never rely on color alone to signal errors.
Handling card data safely
- Do not log values, put them in the URL, or persist them in
localStorage. - Clear state after submit. In production, the number would go to a hosted field or tokenization service, not through app code.
- Validation here only catches typos; it does not prove the card is real.
Test plan
- Unit: Luhn with known valid and invalid numbers; network detection at prefix boundaries; expiry on the current month, last month and an invalid month.
- Linked behavior: typing
37switches grouping to 4-6-5, the max length to 15 and the CVC to 4 digits; changing the number from Amex to Visa makes a 4-digit CVC invalid. - Input: paste with spaces/dashes, mid-string edit keeping the caret, backspace over a space and over the slash.
- Submit: invalid form does not call the callback and focuses the first error; valid form calls it once.
Common mistakes
- Storing derived values (network, errors) separately so they go stale.
- Using
type="number"for the card number. - Showing errors on the first keystroke, which is hostile.
- Validating the CVC with a fixed length of 3.
- Treating a card as expired during its expiry month.
- Forgetting the caret when reformatting.