KatInterview

Linked-Field Payment Card Form with Live Validation

StringsModel answer
MediumModel answerStringsfrontendform-validationluhn

Last 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.