Payment Card Input Controller with Cross-Field Validation

Medium · Software Engineering Fundamentals · Frontend Engineer · Onsite

Problem Statement

Implement the pure state, formatting, caret-tracking, and cross-field validation logic for an interactive payment card checkout form.

You are given NETWORKS (mapping "amex", "visa", "mastercard", and "discover" to their prefixes, lengths, groups, and cvc digit counts) and UNKNOWN (groups: [4, 4, 4, 4, 3], cvc: 3), used while a card number's brand is undecided or unrecognized. Because the fields are coupled, editing the card number dynamically governs digit grouping, maximum card length, and required security-code length (4 digits for "amex", 3 digits otherwise).

Implement the following functions and controller class:

  1. detect_network(digits) -> Optional[str]:

    • Match the leading ASCII digits ('0'–'9') of digits against each network's inclusive (low, high) integer prefix ranges, where a range's width is len(str(low)).
    • Return the matching network name, or None if fewer than len(str(low)) digits have been entered (for example, "3", "5", or "222"), non-ASCII-digit characters appear in the prefix slice, or no range matches.
  2. format_number(digits, network) -> str:

    • Partition digits into chunks defined by NETWORKS[network]["groups"] (or UNKNOWN["groups"] when network is None), join non-empty chunks with single spaces, and never emit a trailing space ("" returns "").
  3. luhn_valid(digits) -> bool:

    • Return True if digits is a non-empty string of ASCII digits whose Luhn mod-10 checksum equals 0 (starting from the rightmost digit at index 0, double every odd-indexed digit, subtract 9 if > 9, and sum all digits); otherwise return False.
  4. Caret-preserving field editors:

    • edit_number(previous, text, caret) -> Tuple[str, int]: given the prior formatted value previous and the raw post-edit (text, caret) reported by an input element:
      • Clamp caret to [0, len(text)], strip all non-ASCII-digit characters, and count how many ASCII digits appeared left of caret.
      • Separator backspace rule: if text contains the exact same ASCII digits as previous, len(text) < len(previous), and at least one digit lies left of caret, also delete the digit immediately left of caret so pressing Backspace after a space deletes a digit instead of getting stuck.
      • Detect the network on the resulting digits, truncate to that network's maximum digit capacity (sum(groups)), regroup with format_number, and place new_caret immediately after the preserved count of leading digits (0 when 0 digits precede it).
    • edit_expiry(previous, text, caret) -> Tuple[str, int]: apply the same ASCII-digit extraction, separator-backspace handling, and digit-anchored caret rule for an MM/YY input capped at 4 digits, inserting "/" after the second digit only once at least 3 digits are present ("0", "08", "08/3", "08/30").
    • edit_cvc(previous, text, caret) -> Tuple[str, int]: apply the same ASCII-digit extraction, cap at 4 digits, and return (digits, new_caret).
  5. validate(values, today) -> Dict[str, str]:

    • Given values with keys "number", "name", "expiry", "cvc" and today = (year, month), return {field: error_code} for invalid fields ({} when valid). Check rules per field in this exact priority order:
      • "number": "required" (zero digits), "unknown_network" (detect_network is None), "wrong_length" (digit count not in NETWORKS[network]["lengths"]), "checksum" (fails luhn_valid).
      • "name": "required" (name.strip() == ""), "invalid" (contains zero .isalpha() characters).
      • "expiry": "required" (expiry == ""), "format" (not 4 digits formatted as MM/YY), "month" (month outside 01..12), "expired" ((2000 + yy, mm) < today).
      • "cvc": "required" (cvc == ""), "wrong_length" (contains non-ASCII digits, or length differs from 4 for "amex" and 3 for all other networks including None).
  6. CardForm(today, on_submit):

    • Initialize values to "" for "number", "name", "expiry", and "cvc".
    • input(field, text, caret) -> int: format and store field ("name" keeps text unchanged while typing and clamps caret to [0, len(text)]) and return new_caret.
    • blur(field) -> None: mark field as having lost focus.
    • network() -> Optional[str]: return the detected network for values["number"].
    • errors() -> Dict[str, str]: return validate(self.values, self.today).
    • visible_errors() -> Dict[str, str]: return errors only for fields that have been blurred, or for all invalid fields once submit() has been attempted.
    • submit() -> bool: mark the form as submit-attempted; if errors() is non-empty, return False without invoking on_submit; otherwise pass {"number": raw_digits, "network": network_name, "name": stripped_name, "exp_month": int_month, "exp_year": 2000 + int_yy, "cvc": cvc_str} to on_submit and return True.

Examples

Example 1

Input:

r1 = edit_number("5412 7500", "54812 7500", 3)
r2 = edit_number("5412 7500", "54127500", 4)
r3 = edit_expiry("08", "083", 3)
r4 = edit_expiry("08/3", "083", 2)

Output: - r1 == ("5481 2750 0", 3) - r2 == ("5417 500", 3) - r3 == ("08/3", 4) - r4 == ("03", 1)

Explanation: In r1, inserting '8' leaves 3 digits ("548") before the cursor, so after regrouping "548127500" into 4-4-4-4 Mastercard chunks, the cursor stays at index 3. In r2 and r4, Backspace erased only the " " or "/" separator (len(text) < len(previous) with identical digits), so the digit right before the cursor is also removed.

Example 2

Input:

submitted = []
form = CardForm((2026, 6), submitted.append)
form.input("number", "5412750012345675", 16)
form.input("name", "Maya Lin ", 9)
form.input("expiry", "0929", 4)
form.input("cvc", "789", 3)
for f in ("number", "name", "expiry", "cvc"):
    form.blur(f)
before_switch = (form.network(), form.visible_errors())

form.input("number", "341122334455664", 15)
after_switch = (form.network(), form.visible_errors(), form.submit())

form.input("cvc", "7890", 4)
ok = form.submit()

Output: - before_switch == ("mastercard", {}) - after_switch == ("amex", {"cvc": "wrong_length"}, False) - ok == True - submitted == [{"number": "341122334455664", "network": "amex", "name": "Maya Lin", "exp_month": 9, "exp_year": 2029, "cvc": "7890"}]

Explanation: Switching "number" from a 16-digit Mastercard to a 15-digit Amex number immediately changes the derived network to "amex". Because "cvc" was already blurred, visible_errors() immediately flags "789" as "wrong_length" (3 != 4) and blocks submission until "7890" is entered; on valid submission, trailing whitespace on "Maya Lin " is stripped.

Constraints

  • Only ASCII digits '0' through '9' count as digits (Unicode superscripts or symbols must be ignored by digit filters and rejected by luhn_valid).
  • A card expiring in (year, month) remains valid throughout that entire month: it is "expired" if and only if (year, month) < today.
  • Cardholder names may contain spaces, hyphens, apostrophes, or accented Unicode letters so long as at least one .isalpha() character is present.
  • edit_cvc allows up to 4 digits regardless of the current card number so user input is never truncated if the shopper updates the CVC before changing the card number to Amex.

Step-by-step walkthrough

  1. Clarify the rules and separate logic from the DOM

    In a front-end interview, you build a browser component, yet almost every hard bug lives in pure logic: recognizing the card network, regrouping digits without jumping the cursor, timing error messages politely, and re-validating the security code whenever the card number changes. Writing that logic as plain functions plus one small state controller (CardForm) makes every rule easy to test without a browser, and trivial to wire up to HTML inputs afterward.

    Before writing code, confirm the open product questions with your interviewer. If they tell you to choose sensible defaults, state your choices clearly up front:

    Question                      Decision and reason
    ----------------------------  ----------------------------------------------------------------------
    Supported card networks       Visa, Mastercard, Amex, Discover; any other prefix -> "unknown_network"
    While network is unknown      Group by 4 (up to 19 digits) and expect a 3-digit CVC
    When errors appear            Only after a field loses focus (blur) or after a submit click; once
                                  visible, re-check on every keystroke so fixed errors vanish right away
    Number grouping               4-4-4-4-3 for 16-to-19-digit cards, 4-6-5 for 15-digit Amex
    Auto-advance focus            No: unexpected focus jumps confuse keyboard and screen-reader users
                                  and make fixing a typo at the end of a field frustrating
    Accessibility & autofill      Explicit <label>, autocomplete="cc-*", type="text" + inputmode="numeric",
                                  and aria-invalid + aria-describedby linking each input to its error
    

    Here, linked fields means that typing into the card number field changes three rules at once: how the number itself is spaced, its maximum length, and whether the security code (CVC) needs 3 digits or 4 digits (Amex).

  2. Separate stored state from derived state

    A derived value is any piece of information that can be calculated purely from other state you already hold, much like a SUM cell in a spreadsheet. Deciding what to store versus what to compute on the fly is what keeps linked fields bug-free:

    STORED STATE (source of truth)            DERIVED ON EVERY READ (never stored)
    ------------------------------------      --------------------------------------------------
    values = {                                network()        <- detect_network(values["number"])
      "number": "3411 223344 55664",          errors()         <- validate(values, today)
      "name":   "Maya Lin",                   visible_errors() <- errors filtered by touched/submitted
      "expiry": "09/29",
      "cvc":    "789",
    }
    touched   = {"number", "cvc", ...}
    submitted = False
    

    Why not store self.network or self.cvc_error as separate fields updated inside the number input's handler? Because a user can also change the card number by pasting, browser autofill, or clicking a reset button. If any path updates values["number"] and forgets to refresh cvc_error, an Amex card can slip through with a 3-digit Visa CVC rule. Recomputing network() and errors() from self.values on every read makes stale state impossible, and because a card number is at most 19 digits, recomputing takes microseconds.

  3. Detect the card network from prefix ranges

    Card issuers identify networks using an issuer identification number (IIN), which is the leading prefix of digits on the card. Storing those rules in a table (NETWORKS) rather than a chain of if/elif branches keeps all per-network settings in one place.

    Two subtle cases matter during prefix matching:

    1. Incomplete prefixes must wait: Mastercard's 2221–2720 range is 4 digits wide. If the user has only typed "222", we do not have 4 digits yet, so detect_network("222") must return None instead of guessing early.
    2. ASCII digits only: Python's str.isdigit() returns True for Unicode superscripts such as "²", which then crash int("²"). Comparing "0" <= char <= "9" accepts only standard ASCII digits 0 through 9.
    # NETWORKS: maps network_name -> {
    #   "prefixes": list of (low_int, high_int) inclusive ranges of equal digit width,
    #   "lengths": allowed total digit counts,
    #   "groups": visual chunk sizes whose sum is the max allowed digit count,
    #   "cvc": required security-code length
    # }
    NETWORKS = {
        "amex": {"prefixes": [(34, 34), (37, 37)], "lengths": [15], "groups": [4, 6, 5], "cvc": 4},
        "visa": {"prefixes": [(4, 4)], "lengths": [13, 16, 19], "groups": [4, 4, 4, 4, 3], "cvc": 3},
        "mastercard": {"prefixes": [(51, 55), (2221, 2720)], "lengths": [16], "groups": [4, 4, 4, 4], "cvc": 3},
        "discover": {
            "prefixes": [(6011, 6011), (644, 649), (65, 65)],
            "lengths": [16, 17, 18, 19],
            "groups": [4, 4, 4, 4, 3],
            "cvc": 3,
        },
    }
    
    # Fallback formatting and CVC rules while the card network is not yet known (up to 19 digits, 3-digit CVC).
    UNKNOWN = {"prefixes": [], "lengths": [], "groups": [4, 4, 4, 4, 3], "cvc": 3}
    
    
    def is_ascii_digit(char: str) -> bool:
        # Compare ASCII bounds directly because str.isdigit() accepts superscripts like "²" that fail int().
        return len(char) == 1 and "0" <= char <= "9"
    
    
    def digits_only(text: str) -> str:
        # Strip spaces, dashes, slashes, and any accidental letters down to raw ASCII digits.
        kept_digits = []
        for char in text:
            if is_ascii_digit(char):
                kept_digits.append(char)
        return "".join(kept_digits)
    
    
    def detect_network(digits: str) -> Optional[str]:
        """Network name whose prefix range matches the start of digits, or None."""
        for name, rules in NETWORKS.items():
            for low, high in rules["prefixes"]:
                prefix_width = len(str(low))
                # Wait until the user has typed at least prefix_width digits (e.g. "222" is still undecided).
                if len(digits) < prefix_width:
                    continue
                prefix_slice = digits[:prefix_width]
                if not all(is_ascii_digit(ch) for ch in prefix_slice):
                    continue
                prefix_value = int(prefix_slice)
                if low <= prefix_value <= high:
                    return name
        return None
    
    
    def rules_for(network: Optional[str]) -> Dict:
        if network is None:
            return UNKNOWN
        return NETWORKS[network]
    
    
    def max_digits_for(network: Optional[str]) -> int:
        # The visual groups sum to the longest card number allowed for that network.
        return sum(rules_for(network)["groups"])
    
  4. Format numbers and expiry dates without losing the caret

    The caret is the blinking text cursor inside an input box. Whenever your code overwrites input.value in a browser to insert spaces, the browser resets the caret to the very end of the string. If a user clicks into the middle of "4242 4242 42" to insert a missing digit, jumping the caret to the end scrambles their next keystroke.

    Character offsets cannot preserve the caret because spaces appear and move around. Instead, anchor the caret by counting digits:

    1. In the raw text reported by the browser right after the edit, count how many digits sit to the left of caret (digits_before_caret).
    2. Strip non-digits, cap the length at the network's maximum, and re-insert separator spaces (format_number).
    3. Scan the newly formatted string until you have passed digits_before_caret digits, and place the caret right there.
    Example 1: Typing "8" after "54" in the middle of a Mastercard number ("|" marks the caret)
      previous : "54|12 7500"
      raw edit : "548|12 7500"      (caret = 3 -> 3 digits to the left of "|")
      regrouped: "548|1 2750 0"     (after 3rd digit -> new caret = 3, NOT 11 at the end)
    
    Example 2: Pasting "1111-2222" at caret 4 of "5412 7500"
      raw edit : "54121111-2222| 7500"  (caret = 13 -> 12 digits to the left of "|")
      regrouped: "5412 1111 2222| 7500" (after 12th digit -> new caret = 14, skipping 2 spaces)
    

    One edge case remains: pressing Backspace right after a separator (like "5412 |7500"). The browser deletes the space ("5412|7500"), which leaves the exact same digits ("54127500") in a shorter string. If we simply reformat "54127500", the space pops right back and Backspace feels broken! Whenever digits == digits_only(previous) and len(text) < len(previous), we also delete the digit immediately before the caret:

    Example 3: Pressing Backspace right after the space
      previous : "5412 |7500"   (len = 9, digits = "54127500")
      raw edit : "5412|7500"    (len = 8, digits = "54127500", digits_before_caret = 4)
      fix      : same digits + shorter text -> delete 4th digit -> "5417500", digits_before_caret = 3
      regrouped: "541|7 500"    (new caret = 3)
    

    The expiry field uses the exact same helper, adding "/" only once a third digit exists ("12" stays "12", "123" becomes "12/3") so the user never has to backspace over a trailing slash. The CVC field keeps up to 4 digits even when the card is currently Visa, because the user might paste an Amex card number afterward.

    def format_number(digits: str, network: Optional[str]) -> str:
        """Digits split into the network's groups, joined by single spaces, no trailing space."""
        groups = []
        start = 0
        for group_size in rules_for(network)["groups"]:
            # Stop as soon as all typed digits are placed so we never emit a trailing space.
            if start >= len(digits):
                break
            groups.append(digits[start:start + group_size])
            start += group_size
        return " ".join(groups)
    
    
    def caret_after_digits(formatted: str, digit_count: int) -> int:
        """String index right after the digit_count-th digit in formatted (0 when digit_count is 0)."""
        if digit_count <= 0:
            return 0
    
        digits_seen = 0
        for index, char in enumerate(formatted):
            if is_ascii_digit(char):
                digits_seen += 1
                if digits_seen == digit_count:
                    return index + 1
        return len(formatted)
    
    
    def digits_after_edit(previous: str, text: str, caret: int) -> Tuple[str, int]:
        """Extract raw digits after an edit and how many digits sit to the left of the caret."""
        # Clamp caret into [0, len(text)] so negative indices never slice from the right in Python.
        safe_caret = max(0, min(caret, len(text)))
        digits = digits_only(text)
        digits_before_caret = len(digits_only(text[:safe_caret]))
    
        # Special case: Backspace right after a space or "/" removes only the separator, leaving the exact
        # same digits in a shorter string. Delete the digit just before the caret too so Backspace does not feel stuck.
        same_digits = digits == digits_only(previous)
        text_got_shorter = len(text) < len(previous)
        if same_digits and text_got_shorter and digits_before_caret > 0:
            delete_index = digits_before_caret - 1
            digits = digits[:delete_index] + digits[delete_index + 1:]
            digits_before_caret -= 1
    
        return digits, digits_before_caret
    
    
    def edit_number(previous: str, text: str, caret: int) -> Tuple[str, int]:
        """Handle an input event on the card number field and return (formatted_value, new_caret)."""
        digits, digits_before_caret = digits_after_edit(previous, text, caret)
        # Detect network before truncating; prefixes need at most 4 digits while max length is at least 15.
        network = detect_network(digits)
        digits = digits[:max_digits_for(network)]
        digits_before_caret = min(digits_before_caret, len(digits))
    
        formatted = format_number(digits, network)
        new_caret = caret_after_digits(formatted, digits_before_caret)
        return formatted, new_caret
    
    
    def edit_expiry(previous: str, text: str, caret: int) -> Tuple[str, int]:
        """Format an MM/YY field (up to 4 digits, inserting '/' only once a 3rd digit exists)."""
        digits, digits_before_caret = digits_after_edit(previous, text, caret)
        digits = digits[:4]
        digits_before_caret = min(digits_before_caret, len(digits))
    
        # Only add "/" once the year starts ("12" -> "12", "123" -> "12/3") so there is no trailing slash to fight.
        if len(digits) > 2:
            formatted = digits[:2] + "/" + digits[2:]
        else:
            formatted = digits
    
        new_caret = caret_after_digits(formatted, digits_before_caret)
        return formatted, new_caret
    
    
    def edit_cvc(previous: str, text: str, caret: int) -> Tuple[str, int]:
        """Digits only, capped at 4 digits (even for Visa, in case the user changes the card to Amex next)."""
        digits, digits_before_caret = digits_after_edit(previous, text, caret)
        digits = digits[:4]
        new_caret = min(digits_before_caret, len(digits))
        return digits, new_caret
    
  5. Validate each field and link CVC to the card network

    Each validator returns a short machine-readable error code (like "wrong_length" or "checksum") or None when valid. Returning codes rather than English sentences makes unit tests clean and lets the UI translate messages into any language.

    • Card number (number_error): Check "required", "unknown_network", "wrong_length", and finally the Luhn checksum, an error-detecting formula built into payment card numbers to catch single-digit typos and most adjacent swaps. Starting from the rightmost digit (position 0), double every odd-positioned digit (positions 1, 3, 5, ...). If doubling produces a two-digit number (10 to 18), subtract 9 (which is identical to adding its two digits: 16 - 9 = 7 = 1 + 6). Sum everything; a valid card totals a multiple of 10:
    Digits (Visa test card):  4   2   4   2   ... (eight "4, 2" pairs)
    Position from right    : 15  14  13  12   ...  1   0
    Doubled on odd pos     :  8   2   8   2   ...  8   2
    Sum = 8 * 8 + 8 * 2 = 64 + 16 = 80 -> 80 % 10 == 0 (valid!)
    Change last digit to 1 : sum becomes 79 -> 79 % 10 != 0 ("checksum")
    
    • Name (name_error): Must not be blank after stripping spaces, and must contain at least one letter (char.isalpha()). Avoid strict ASCII regexes: real cardholder names contain accents, hyphens, apostrophes, and non-Latin scripts ("José Núñez-O'Neil").
    • Expiry (expiry_error): Must match MM/YY with 01 <= month <= 12. A card expires at the end of its printed month, so when today is (2026, 11), "11/26" is still valid while "10/26" is "expired". Always compare (year, month) integer tuples—never raw "MM/YY" strings, where "12/25" > "01/27" alphabetically!
    • Security code (cvc_error): Must be all digits and match rules_for(network)["cvc"] (4 for Amex, 3 otherwise). Passing the number's network into cvc_error is the cross-field validation link.
    def luhn_valid(digits: str) -> bool:
        """Luhn checksum of a non-empty digit string (False for "")."""
        if not digits:
            return False
    
        total = 0
        # Walk from right to left so odd positions (1, 3, 5, ...) are always every second digit from the check digit,
        # regardless of whether the card has 15 digits (Amex) or 16 digits (Visa/Mastercard).
        for position_from_right, char in enumerate(reversed(digits)):
            if not is_ascii_digit(char):
                return False
            value = int(char)
            if position_from_right % 2 == 1:
                value *= 2
                # Subtracting 9 from 10..18 equals summing the two digits (e.g. 14 -> 1 + 4 = 5 = 14 - 9).
                if value > 9:
                    value -= 9
            total += value
    
        return total % 10 == 0
    
    
    def number_error(digits: str, network: Optional[str]) -> Optional[str]:
        # Check rules from most basic to most specific so empty/incomplete numbers report clear reasons.
        if not digits:
            return "required"
        if network is None:
            return "unknown_network"
        if len(digits) not in NETWORKS[network]["lengths"]:
            return "wrong_length"
        if not luhn_valid(digits):
            return "checksum"
        return None
    
    
    def name_error(name: str) -> Optional[str]:
        if not name.strip():
            return "required"
        # Accept accents, hyphens, and apostrophes (e.g. "José Núñez-O'Neil") as long as at least one letter exists.
        for char in name:
            if char.isalpha():
                return None
        return "invalid"
    
    
    def expiry_error(expiry: str, today: Tuple[int, int]) -> Optional[str]:
        if not expiry:
            return "required"
        digits = digits_only(expiry)
        if len(digits) != 4 or expiry != digits[:2] + "/" + digits[2:]:
            return "format"
    
        month = int(digits[:2])
        year = 2000 + int(digits[2:])
        if month < 1 or month > 12:
            return "month"
        # Compare (year, month) tuples with "<", not "<=": a card expiring in 11/26 stays valid all of Nov 2026.
        if (year, month) < today:
            return "expired"
        return None
    
    
    def cvc_error(cvc: str, network: Optional[str]) -> Optional[str]:
        if not cvc:
            return "required"
        # Cross-field link: required CVC length (4 for Amex, 3 otherwise) is derived from the card number's network.
        expected_length = rules_for(network)["cvc"]
        if digits_only(cvc) != cvc or len(cvc) != expected_length:
            return "wrong_length"
        return None
    
    
    def validate(values: Dict[str, str], today: Tuple[int, int]) -> Dict[str, str]:
        """Error code per invalid field; {} means valid. today is (year, month)."""
        number_digits = digits_only(values["number"])
        network = detect_network(number_digits)
    
        raw_errors = {
            "number": number_error(number_digits, network),
            "name": name_error(values["name"]),
            "expiry": expiry_error(values["expiry"], today),
            "cvc": cvc_error(values["cvc"], network),
        }
    
        errors = {}
        for field, code in raw_errors.items():
            if code is not None:
                errors[field] = code
        return errors
    
  6. Build the CardForm state controller and error timing

    Showing "wrong_length" on the very first digit a user types feels hostile, whereas waiting until form submission gives feedback too late. The sweet spot is "reward early, punish late":

    • While a user is typing into an untouched field for the first time, visible_errors() hides that field's error.
    • As soon as the user leaves a field (blur(field) adds it to self.touched) or clicks submit (self.submitted = True), errors for those fields become visible.
    • Because visible_errors() filters a fresh self.errors() call on every read, the moment a user types the digit that fixes an error, the warning disappears immediately without waiting for another blur.

    Also note how name is handled: input("name", ...) preserves trailing spaces as typed (otherwise typing "Ada " on the way to "Ada Lovelace" would eat the space!), and submit() strips outer whitespace only when building the clean payload.

    class CardForm:
        """Minimal stored state for the form; network, errors, and error visibility are derived on read."""
    
        def __init__(self, today: Tuple[int, int], on_submit: Callable[[Dict], None]):
            self.today = today
            self.on_submit = on_submit
            # values: {"number": formatted_str, "name": raw_str, "expiry": formatted_str, "cvc": digit_str}
            self.values = {"number": "", "name": "", "expiry": "", "cvc": ""}
            # touched: set of field names that have lost focus at least once (e.g. {"number", "expiry"})
            self.touched = set()
            self.submitted = False
    
        def input(self, field: str, text: str, caret: int) -> int:
            """Store the formatted value of field and return the new caret position."""
            previous = self.values[field]
            if field == "number":
                value, new_caret = edit_number(previous, text, caret)
            elif field == "expiry":
                value, new_caret = edit_expiry(previous, text, caret)
            elif field == "cvc":
                value, new_caret = edit_cvc(previous, text, caret)
            else:
                # Keep spaces while typing the name ("Ada " before "Lovelace"); strip only on submit.
                value = text
                new_caret = max(0, min(caret, len(text)))
            self.values[field] = value
            return new_caret
    
        def blur(self, field: str) -> None:
            self.touched.add(field)
    
        def network(self) -> Optional[str]:
            return detect_network(digits_only(self.values["number"]))
    
        def errors(self) -> Dict[str, str]:
            return validate(self.values, self.today)
    
        def visible_errors(self) -> Dict[str, str]:
            # Hide errors on untouched fields while typing for the first time; show on blur or after submit.
            shown = {}
            for field, code in self.errors().items():
                if self.submitted or field in self.touched:
                    shown[field] = code
            return shown
    
        def submit(self) -> bool:
            self.submitted = True
            if self.errors():
                return False
    
            number_digits = digits_only(self.values["number"])
            expiry_digits = digits_only(self.values["expiry"])
            self.on_submit({
                "number": number_digits,
                "network": detect_network(number_digits),
                "name": self.values["name"].strip(),
                "exp_month": int(expiry_digits[:2]),
                "exp_year": 2000 + int(expiry_digits[2:]),
                "cvc": self.values["cvc"],
            })
            return True
    
  7. Connect CardForm to browser inputs and trace a linked edit

    In the browser, porting CardForm to JavaScript connects cleanly to four <input> elements. Three HTML details prevent classic bugs:

    • Use type="text" with inputmode="numeric" (for a mobile number pad), never type="number": HTML number inputs strip leading zeros (turning CVC "012" into "12"), show increment arrows, and throw an exception when you call setSelectionRange().
    • Call input.setSelectionRange(caret, caret) immediately after assigning input.value.
    • Wire ARIA attributes (accessibility HTML attributes read by screen readers), setting aria-invalid and pointing aria-describedby to the field's error <span>. Never log card data or store it in localStorage.
    // <label for="cc-number">Card number</label>
    // <input id="cc-number" type="text" inputmode="numeric" autocomplete="cc-number"
    //        aria-describedby="cc-number-error">
    // <span id="cc-number-error" role="alert"></span>
    const form = new CardForm(currentYearMonth(), (payload) => onValidSubmit(payload));
    
    function bindField(field, inputEl) {
      inputEl.addEventListener("input", () => {
        const caret = form.input(field, inputEl.value, inputEl.selectionStart);
        inputEl.value = form.values[field];
        inputEl.setSelectionRange(caret, caret);
        render();
      });
      inputEl.addEventListener("blur", () => {
        form.blur(field);
        render();
      });
    }
    
    function render() {
      const shown = form.visibleErrors();
      for (const field of ["number", "name", "expiry", "cvc"]) {
        const inputEl = document.getElementById(`cc-${field}`);
        inputEl.setAttribute("aria-invalid", field in shown ? "true" : "false");
        document.getElementById(`cc-${field}-error`).textContent =
          shown[field] ? MESSAGES[field][shown[field]] : "";
      }
      document.getElementById("cc-network").textContent = form.network() || "";
      document.getElementById("cc-cvc").placeholder = form.network() === "amex" ? "4 digits" : "3 digits";
    }
    

    Trace Example 2 when a user completes a Mastercard form in June 2026 (today = (2026, 6)) and then replaces the card number with an Amex card:

    User action                                 Stored values                        network()     visible_errors()
    ------------------------------------------  -----------------------------------  ------------  -----------------------
    1. Paste "5412750012345675" in number       number="5412 7500 1234 5675" (c=19)  "mastercard"  {}
    2. Enter "Maya Lin ", "0929", "789"         expiry="09/29", cvc="789"            "mastercard"  {}
    3. Blur all 4 fields                        touched={"number","name",...}        "mastercard"  {}
    4. Paste Amex "341122334455664" in number   number="3411 223344 55664" (c=17)    "amex"        {"cvc": "wrong_length"}
    5. Click Submit                             submitted=True                       "amex"        returns False (blocked)
    6. Type "7890" in cvc, click Submit         cvc="7890"                           "amex"        {} -> calls on_submit!
    

    Even though the user never touched the CVC field in step 4, "cvc": "wrong_length" appeared immediately because visible_errors() derived the CVC requirement from the new Amex number and "cvc" was already in touched.

  8. Complete solution

    from typing import Callable, Dict, Optional, Tuple
    
    # NETWORKS: maps network_name -> {
    #   "prefixes": list of (low_int, high_int) inclusive ranges of equal digit width,
    #   "lengths": allowed total digit counts,
    #   "groups": visual chunk sizes whose sum is the max allowed digit count,
    #   "cvc": required security-code length
    # }
    NETWORKS = {
        "amex": {"prefixes": [(34, 34), (37, 37)], "lengths": [15], "groups": [4, 6, 5], "cvc": 4},
        "visa": {"prefixes": [(4, 4)], "lengths": [13, 16, 19], "groups": [4, 4, 4, 4, 3], "cvc": 3},
        "mastercard": {"prefixes": [(51, 55), (2221, 2720)], "lengths": [16], "groups": [4, 4, 4, 4], "cvc": 3},
        "discover": {
            "prefixes": [(6011, 6011), (644, 649), (65, 65)],
            "lengths": [16, 17, 18, 19],
            "groups": [4, 4, 4, 4, 3],
            "cvc": 3,
        },
    }
    
    # Fallback formatting and CVC rules while the card network is not yet known (up to 19 digits, 3-digit CVC).
    UNKNOWN = {"prefixes": [], "lengths": [], "groups": [4, 4, 4, 4, 3], "cvc": 3}
    
    
    def is_ascii_digit(char: str) -> bool:
        # Compare ASCII bounds directly because str.isdigit() accepts superscripts like "²" that fail int().
        return len(char) == 1 and "0" <= char <= "9"
    
    
    def digits_only(text: str) -> str:
        # Strip spaces, dashes, slashes, and any accidental letters down to raw ASCII digits.
        kept_digits = []
        for char in text:
            if is_ascii_digit(char):
                kept_digits.append(char)
        return "".join(kept_digits)
    
    
    def detect_network(digits: str) -> Optional[str]:
        """Network name whose prefix range matches the start of digits, or None."""
        for name, rules in NETWORKS.items():
            for low, high in rules["prefixes"]:
                prefix_width = len(str(low))
                # Wait until the user has typed at least prefix_width digits (e.g. "222" is still undecided).
                if len(digits) < prefix_width:
                    continue
                prefix_slice = digits[:prefix_width]
                if not all(is_ascii_digit(ch) for ch in prefix_slice):
                    continue
                prefix_value = int(prefix_slice)
                if low <= prefix_value <= high:
                    return name
        return None
    
    
    def rules_for(network: Optional[str]) -> Dict:
        if network is None:
            return UNKNOWN
        return NETWORKS[network]
    
    
    def max_digits_for(network: Optional[str]) -> int:
        # The visual groups sum to the longest card number allowed for that network.
        return sum(rules_for(network)["groups"])
    
    
    def format_number(digits: str, network: Optional[str]) -> str:
        """Digits split into the network's groups, joined by single spaces, no trailing space."""
        groups = []
        start = 0
        for group_size in rules_for(network)["groups"]:
            # Stop as soon as all typed digits are placed so we never emit a trailing space.
            if start >= len(digits):
                break
            groups.append(digits[start:start + group_size])
            start += group_size
        return " ".join(groups)
    
    
    def luhn_valid(digits: str) -> bool:
        """Luhn checksum of a non-empty digit string (False for "")."""
        if not digits:
            return False
    
        total = 0
        # Walk from right to left so odd positions (1, 3, 5, ...) are always every second digit from the check digit,
        # regardless of whether the card has 15 digits (Amex) or 16 digits (Visa/Mastercard).
        for position_from_right, char in enumerate(reversed(digits)):
            if not is_ascii_digit(char):
                return False
            value = int(char)
            if position_from_right % 2 == 1:
                value *= 2
                # Subtracting 9 from 10..18 equals summing the two digits (e.g. 14 -> 1 + 4 = 5 = 14 - 9).
                if value > 9:
                    value -= 9
            total += value
    
        return total % 10 == 0
    
    
    def caret_after_digits(formatted: str, digit_count: int) -> int:
        """String index right after the digit_count-th digit in formatted (0 when digit_count is 0)."""
        if digit_count <= 0:
            return 0
    
        digits_seen = 0
        for index, char in enumerate(formatted):
            if is_ascii_digit(char):
                digits_seen += 1
                if digits_seen == digit_count:
                    return index + 1
        return len(formatted)
    
    
    def digits_after_edit(previous: str, text: str, caret: int) -> Tuple[str, int]:
        """Extract raw digits after an edit and how many digits sit to the left of the caret."""
        # Clamp caret into [0, len(text)] so negative indices never slice from the right in Python.
        safe_caret = max(0, min(caret, len(text)))
        digits = digits_only(text)
        digits_before_caret = len(digits_only(text[:safe_caret]))
    
        # Special case: Backspace right after a space or "/" removes only the separator, leaving the exact
        # same digits in a shorter string. Delete the digit just before the caret too so Backspace does not feel stuck.
        same_digits = digits == digits_only(previous)
        text_got_shorter = len(text) < len(previous)
        if same_digits and text_got_shorter and digits_before_caret > 0:
            delete_index = digits_before_caret - 1
            digits = digits[:delete_index] + digits[delete_index + 1:]
            digits_before_caret -= 1
    
        return digits, digits_before_caret
    
    
    def edit_number(previous: str, text: str, caret: int) -> Tuple[str, int]:
        """Handle an input event on the card number field and return (formatted_value, new_caret)."""
        digits, digits_before_caret = digits_after_edit(previous, text, caret)
        # Detect network before truncating; prefixes need at most 4 digits while max length is at least 15.
        network = detect_network(digits)
        digits = digits[:max_digits_for(network)]
        digits_before_caret = min(digits_before_caret, len(digits))
    
        formatted = format_number(digits, network)
        new_caret = caret_after_digits(formatted, digits_before_caret)
        return formatted, new_caret
    
    
    def edit_expiry(previous: str, text: str, caret: int) -> Tuple[str, int]:
        """Format an MM/YY field (up to 4 digits, inserting '/' only once a 3rd digit exists)."""
        digits, digits_before_caret = digits_after_edit(previous, text, caret)
        digits = digits[:4]
        digits_before_caret = min(digits_before_caret, len(digits))
    
        # Only add "/" once the year starts ("12" -> "12", "123" -> "12/3") so there is no trailing slash to fight.
        if len(digits) > 2:
            formatted = digits[:2] + "/" + digits[2:]
        else:
            formatted = digits
    
        new_caret = caret_after_digits(formatted, digits_before_caret)
        return formatted, new_caret
    
    
    def edit_cvc(previous: str, text: str, caret: int) -> Tuple[str, int]:
        """Digits only, capped at 4 digits (even for Visa, in case the user changes the card to Amex next)."""
        digits, digits_before_caret = digits_after_edit(previous, text, caret)
        digits = digits[:4]
        new_caret = min(digits_before_caret, len(digits))
        return digits, new_caret
    
    
    def number_error(digits: str, network: Optional[str]) -> Optional[str]:
        # Check rules from most basic to most specific so empty/incomplete numbers report clear reasons.
        if not digits:
            return "required"
        if network is None:
            return "unknown_network"
        if len(digits) not in NETWORKS[network]["lengths"]:
            return "wrong_length"
        if not luhn_valid(digits):
            return "checksum"
        return None
    
    
    def name_error(name: str) -> Optional[str]:
        if not name.strip():
            return "required"
        # Accept accents, hyphens, and apostrophes (e.g. "José Núñez-O'Neil") as long as at least one letter exists.
        for char in name:
            if char.isalpha():
                return None
        return "invalid"
    
    
    def expiry_error(expiry: str, today: Tuple[int, int]) -> Optional[str]:
        if not expiry:
            return "required"
        digits = digits_only(expiry)
        if len(digits) != 4 or expiry != digits[:2] + "/" + digits[2:]:
            return "format"
    
        month = int(digits[:2])
        year = 2000 + int(digits[2:])
        if month < 1 or month > 12:
            return "month"
        # Compare (year, month) tuples with "<", not "<=": a card expiring in 11/26 stays valid all of Nov 2026.
        if (year, month) < today:
            return "expired"
        return None
    
    
    def cvc_error(cvc: str, network: Optional[str]) -> Optional[str]:
        if not cvc:
            return "required"
        # Cross-field link: required CVC length (4 for Amex, 3 otherwise) is derived from the card number's network.
        expected_length = rules_for(network)["cvc"]
        if digits_only(cvc) != cvc or len(cvc) != expected_length:
            return "wrong_length"
        return None
    
    
    def validate(values: Dict[str, str], today: Tuple[int, int]) -> Dict[str, str]:
        """Error code per invalid field; {} means valid. today is (year, month)."""
        number_digits = digits_only(values["number"])
        network = detect_network(number_digits)
    
        raw_errors = {
            "number": number_error(number_digits, network),
            "name": name_error(values["name"]),
            "expiry": expiry_error(values["expiry"], today),
            "cvc": cvc_error(values["cvc"], network),
        }
    
        errors = {}
        for field, code in raw_errors.items():
            if code is not None:
                errors[field] = code
        return errors
    
    
    class CardForm:
        """Minimal stored state for the form; network, errors, and error visibility are derived on read."""
    
        def __init__(self, today: Tuple[int, int], on_submit: Callable[[Dict], None]):
            self.today = today
            self.on_submit = on_submit
            # values: {"number": formatted_str, "name": raw_str, "expiry": formatted_str, "cvc": digit_str}
            self.values = {"number": "", "name": "", "expiry": "", "cvc": ""}
            # touched: set of field names that have lost focus at least once (e.g. {"number", "expiry"})
            self.touched = set()
            self.submitted = False
    
        def input(self, field: str, text: str, caret: int) -> int:
            """Store the formatted value of field and return the new caret position."""
            previous = self.values[field]
            if field == "number":
                value, new_caret = edit_number(previous, text, caret)
            elif field == "expiry":
                value, new_caret = edit_expiry(previous, text, caret)
            elif field == "cvc":
                value, new_caret = edit_cvc(previous, text, caret)
            else:
                # Keep spaces while typing the name ("Ada " before "Lovelace"); strip only on submit.
                value = text
                new_caret = max(0, min(caret, len(text)))
            self.values[field] = value
            return new_caret
    
        def blur(self, field: str) -> None:
            self.touched.add(field)
    
        def network(self) -> Optional[str]:
            return detect_network(digits_only(self.values["number"]))
    
        def errors(self) -> Dict[str, str]:
            return validate(self.values, self.today)
    
        def visible_errors(self) -> Dict[str, str]:
            # Hide errors on untouched fields while typing for the first time; show on blur or after submit.
            shown = {}
            for field, code in self.errors().items():
                if self.submitted or field in self.touched:
                    shown[field] = code
            return shown
    
        def submit(self) -> bool:
            self.submitted = True
            if self.errors():
                return False
    
            number_digits = digits_only(self.values["number"])
            expiry_digits = digits_only(self.values["expiry"])
            self.on_submit({
                "number": number_digits,
                "network": detect_network(number_digits),
                "name": self.values["name"].strip(),
                "exp_month": int(expiry_digits[:2]),
                "exp_year": 2000 + int(expiry_digits[2:]),
                "cvc": self.values["cvc"],
            })
            return True
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a credit card form like a small spreadsheet with four input cells (number, name, expiry, cvc) and several formula cells (network, errors, visible_errors). Derived state means any value computed directly from existing state on every read rather than stored in its own variable; meanwhile, the caret (the blinking text cursor) is tracked by counting how many digits sit to its left, treating spaces and slashes as visual decoration rather than real content.

The naive approach stores network and cvcError in separate state variables updated inside the card-number handler, and formats inputs by simply overwriting input.value. That breaks in two ways: pasting or autofilling a new card number can leave cvcError stuck on the old network's rule, and overwriting input.value in the browser teleports the caret to the end of the box while making Backspace get stuck on spaces.

Walk through Example 1 and Example 2 to see how digit-anchored editing and derived validation work together:

  1. Caret-safe mid-field edit: Suppose "5412 7500" becomes "54812 7500" with the caret at index 3 right after "548". There are 3 digits left of the caret, raw digits "548127500" regroup for Mastercard into "5481 2750 0", and placing the caret right after the 3rd digit puts it at index 3 ("548|1 2750 0") instead of jumping to index 11.
  2. Cross-field link: Suppose a blurred Mastercard form holds CVC "789" (0 errors) and the user pastes an Amex number "341122334455664". On the very next read, validate detects "amex" from "34...", sees that Amex requires a 4-digit CVC, and immediately surfaces {"cvc": "wrong_length"} without the CVC input ever being edited.

Complexity

  • Time: Every input edit and every validate call runs in O(L) time, where L is the length of the field strings. Each helper makes a constant number of single left-to-right passes—one to strip digits, one to check the constant-size NETWORKS prefix table, one to regroup digits or run the Luhn checksum (an error-detecting digit sum that catches single-digit typos), and one to place the caret. Since a card number has at most 19 digits plus 4 spaces (L <= 23) and name is short, every keystroke does tiny, practically constant work.
  • Space: O(L) auxiliary space per edit to build the cleaned digit string and formatted output string, plus O(1) persistent state on CardForm (four field strings, a touched set of at most four field names, and one boolean submitted flag).

Edge cases

  • Unknown card network: Numbers that match no known issuer prefix (the leading digits that identify a card brand, such as 4 for Visa or 34/37 for Amex) still format cleanly in groups of 4 up to 19 digits, validate CVC against 3 digits, and report "unknown_network" on the number field.
  • Undecided short prefixes: Inputs like "3", "5", or "222" do not have enough digits yet to match 34/37, 51–55, or 2221–2720, so detect_network returns None rather than guessing prematurely.
  • Multiple valid lengths on one network: Visa permits 13, 16, or 19 digits and Discover permits 16 through 19 digits, so formatting caps input at the maximum length (19) rather than stopping at 16.
  • Backspace vs. forward Delete on a separator: Backspace right after a space or "/" produces the same digits in a shorter string, so digits_after_edit removes the digit left of the caret. Note that forward Delete right before a separator (or overwriting a selection like "2 4" with "24") produces the same (previous, text) signature; in a real browser, checking InputEvent.inputType ("deleteContentBackward" vs. "deleteContentForward") distinguishes them exactly.
  • Typing "/" manually in expiry: Because edit_expiry strips non-digits, typing "1/27" for January yields "12/7". Production forms often interpret "/" after a single digit "1" as "01/", or auto-pad single digits "2" through "9" ("4" -> "04").
  • Expiring in the current month: Payment cards remain valid through the last day of their printed month, so when today is (2026, 11), "11/26" is valid ((2026, 11) < (2026, 11) is False) and "10/26" is "expired".
  • International cardholder names: Names like "José Núñez-O'Neil" contain accents, hyphens, and apostrophes; requiring at least one isalpha() character accepts all scripts while rejecting " " or "1234".

Common mistakes

  • Storing network, cvcError, or isFormValid as separate state variables: Updating them inside one event listener means paste, autofill, or programmatic resets leave them out of sync.
  • Overwriting input.value without calling setSelectionRange: The browser jumps the caret to the end of the input on every mid-string edit.
  • Tracking caret offset by raw character index instead of digit count: Inserted or removed spaces shift character positions under the cursor.
  • Using <input type="number"> for card numbers or CVC: Number inputs strip leading zeros (turning CVC "012" into "12"), show spinner arrows, and throw an error on setSelectionRange. Use type="text" with inputmode="numeric".
  • Doubling Luhn digits from the left instead of the right: Counting from the left only works on even-length 16-digit cards and breaks every 15-digit Amex number.
  • Truncating or wiping the CVC value when the card network changes: Never silently destroy user input; keep all 4 typed digits and let validation flag "wrong_length" if needed.
  • Logging card numbers or saving form drafts to localStorage: Sensitive payment fields must never touch browser storage, URLs, or analytics logs.

Follow-up questions

  • What happens when someone pastes a formatted card number containing hyphens or spaces directly into the middle of partial input? Because edit_number inspects the resulting text and caret rather than the clipboard event itself, mid-string pastes already work with zero special-case code. It counts how many digits appear before caret in the combined string, strips all spaces and dashes, truncates to the detected network's maximum length, regroups, and places the caret right after that digit count. For instance, pasting "1111-2222" at index 4 of "5412 7500" yields "54121111-2222 7500" with 12 digits before the caret, which formats to "5412 1111 2222 7500" with the caret at index 14. If truncating overflow digits silently feels surprising on paste, you can inspect inputType === "insertFromPaste" and surface a warning when excess digits were dropped.
  • How could you turn this controller into a schema-driven form engine that supports arbitrary interdependent fields? Represent each field declaratively with a format(previous, text, caret, values) function and an ordered list of validator(value, values) -> Optional[str] functions that receive the entire values dictionary. The generic form controller still stores only values, touched, and submitted, and derives errors() by running every field's validator list against the current values snapshot on each read. Because every validator sees all fields, cross-field rules like matching passwords, start/end date ranges, or Amex CVC length require no manual dependency subscriptions and can never go stale.
  • How does the frontend architecture change when PCI rules forbid raw card digits from touching your application scripts? Under strict PCI DSS (Payment Card Industry Data Security Standard) requirements, you replace raw <input> elements for the card number, expiry, and CVC with hosted fields—isolated <iframe> elements served directly from your payment processor's domain so the browser's same-origin policy blocks your JavaScript from reading the digits. Inside those iframes, the processor's code handles formatting, caret placement, network detection, and Luhn checks, sending your parent page safe metadata events such as {brand: "amex", complete: false, error: "wrong_length"} via postMessage. On submit, your page keeps only the non-sensitive cardholder name, asks the SDK to exchange the iframe contents for a single-use token (a random stand-in ID), and sends that token to your backend alongside a strict Content Security Policy (CSP) (an HTTP header that restricts which domains can run scripts on your checkout page).
  • What testing strategy verifies that editing the card number immediately updates security-code validation? Test across three layers so both logic and DOM wiring are covered. First, write a fast unit test on validate confirming that cvc="789" returns {} with a valid Mastercard number and {"cvc": "wrong_length"} with a valid Amex number. Second, write a state-transition test on CardForm that fills a valid Mastercard form, blurs all four fields, edits only "number" to an Amex number, asserts visible_errors() == {"cvc": "wrong_length"} and submit() is False, then updates "cvc" to "7890" and confirms submit() is True. Third, run one browser integration test (e.g., with Playwright) verifying that typing an Amex number into the DOM updates the CVC input's aria-invalid="true" attribute and visible error text without touching the CVC element.

Follow-up questions

Similar questions

More Cohere interview questions

All 14 Cohere questions →