Virtual Payment Cards: Trade-Offs, Validation Rules, and Filter Debugging

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

This engineering case study explores virtual payment card numbers—substitute card numbers generated on demand by a card-issuing bank and mapped to an existing primary cardholder account so online merchants never receive the number embossed on the physical card.

The exercise spans three linked stages:

  1. Product & Security Trade-Offs: Evaluate the advantages, operational costs, and post-checkout failure modes (such as refunds, recurring subscriptions, merchant breaches, and in-person card verification) for cardholders, merchants, and card issuers, and state when virtual card numbers are or are not appropriate.
  2. Manual Rule Verification: Independently test candidate strings (Card 1 through Card 5 in Example 1) against all three validation rules below, showing the Luhn calculation step by step.
  3. Validator Debugging & Implementation: Diagnose why the defective starter implementation below fails on the candidate batch, uncover latent bugs that other malformed or odd-length inputs would trigger, and implement a correct filter_cards function.
def filter_cards(numbers: List[str]) -> List[str]:

A candidate string in numbers is valid if and only if, after stripping ASCII space characters (" "), it satisfies all three conditions:

  • R1 (Length & Digits): Contains 16 ASCII digits ('0'–'9') and zero other characters.
  • R2 (Luhn Checksum): Moving right-to-left starting at the final digit (the check digit), multiply every alternate digit (2nd, 4th, 6th, ... from the right) by 2; if any doubled value is greater than 9, subtract 9 from it. The sum of all resulting values must be divisible by 10.
  • R3 (Network Prefix): Begins with '4' or '5'.

Return a list containing every valid entry from numbers unchanged (preserving original spaces, input ordering, and duplicate valid entries). Malformed inputs—including empty strings, non-space whitespace, hyphens, letters, or non-ASCII characters—must be rejected cleanly without raising an exception.

For Part 3, consider this defective prototype:

def luhn_ok(number: str) -> bool:
    total = 0
    for i, ch in enumerate(number):
        d = int(ch)
        if i % 2 == 0:
            d *= 2
            if d > 9:
                d -= 9
        total += d
    return total % 10 == 0


def filter_cards(numbers: list[str]) -> list[str]:
    result = []
    for raw in numbers:
        number = raw.replace(" ", "")
        if len(number) == 16 or luhn_ok(number) and number[0] in "45":
            result.append(raw)
    return result

Examples

Example 1

Label Candidate String
Card 1 "4242 4242 4242 4242"
Card 2 "4242 4242 4242 4245"
Card 3 "5600 0000 0000 0029"
Card 4 "3700 0000 0000 0007"
Card 5 "5222 2222 2222 225"
Input: numbers = [
  "4242 4242 4242 4242",
  "4242 4242 4242 4245",
  "5600 0000 0000 0029",
  "3700 0000 0000 0007",
  "5222 2222 2222 225"
]
Output: ["4242 4242 4242 4242", "5600 0000 0000 0029"]

Checking all three rules on each normalized candidate: - Card 1 (4242424242424242): 16 digits (R1 pass); eight doubled 4s give 64 plus eight undoubled 2s give 16 for Luhn sum 80 (R2 pass); starts with '4' (R3 pass) — kept. - Card 2 (4242424242424245): 16 digits (R1 pass) and starts with '4' (R3 pass), but increasing the rightmost digit from 2 to 5 makes the Luhn sum 83 (R2 fail) — rejected. - Card 3 (5600000000000029): 16 digits (R1 pass); doubled '5' gives 10 - 9 = 1, undoubled '6' gives 6, doubled '2' gives 4, and check digit '9' gives 9 for Luhn sum 20 (R2 pass); starts with '5' (R3 pass) — kept. - Card 4 (3700000000000007): 16 digits (R1 pass) and Luhn sum 6 + 7 + 7 = 20 (R2 pass), but starts with '3' (R3 fail) — rejected. - Card 5 (522222222222225): Luhn sum 5 + 12 + 28 + 5 = 50 (R2 pass) and starts with '5' (R3 pass), but has only 15 digits (R1 fail) — rejected.

Example 2

Input: numbers = [
  " 4242  4242 4242 4242 ",
  "4242-4242-4242-4242",
  "4242 4242 4242 424a",
  "   "
]
Output: [" 4242  4242 4242 4242 "]

The first string normalizes to "4242424242424242" (passing R1, R2, and R3) and is returned with its exact original spacing. Hyphens, letters, and blank strings fail R1 without throwing errors.

Constraints

  • 0 <= len(numbers) <= 10^4
  • Each string in numbers has length 0 <= len(raw) <= 100 and may contain arbitrary ASCII or Unicode characters.
  • Only ASCII spaces (" ") are ignored when normalizing; tabs, newlines, dashes, letters, and non-ASCII numerals invalidate an entry.
  • Returned entries must match the exact input strings and preserve both relative order and duplicates.

Step-by-step walkthrough

  1. Understand the three-part case study and clarify edge rules

    This case study connects product thinking, manual verification, and debugging around virtual card numbers — card numbers generated on demand by a card issuer and linked to a customer's real account so merchants never see the physical card number.

    A string in numbers is acceptable if, after removing spaces (" "), it passes all three rules:

    • R1 (length & characters): consists of exactly 16 ASCII digits (0–9) and nothing else.
    • R2 (Luhn checksum): starting at the rightmost digit (position 0, the check digit) and moving left, double every second digit (positions 1, 3, 5, ...), subtract 9 from any doubled value above 9, and check that the sum of all resulting digits is divisible by 10.
    • R3 (prefix): starts with '4' or '5'.

    Clarifying choices used throughout our implementation:

    • Only ASCII space " " is stripped; tabs, newlines, hyphens, letters, or non-ASCII symbols fail R1 silently without raising an exception.
    • filter_cards returns the original strings (preserving spaces, input order, and duplicates).
  2. Part 1 · Weigh virtual card trade-offs across all three parties

    The central security idea of virtual cards is blast-radius containment: if a merchant is breached today or a year from now, closing or capping that single virtual number protects the physical card and every other merchant relationship.

    Party Benefits Costs and post-purchase failure scenarios
    Customer A leaked merchant database exposes only one revocable number. Per-card spend caps or expiration dates block surprise trial renewals or overcharges without replacing the physical plastic card. Post-close refunds need issuer routing back to the underlying account. Desired subscriptions fail when a virtual card expires. In-person presentation (hotel check-in, rental car counter, box-office pickup requiring the card used online) fails when no matching physical card exists.
    Merchant Standard 16-digit card format works through existing payment rails with zero checkout redesign; stolen card-on-file databases become useless quickly once deactivated. Higher involuntary churn when locked or expiring virtual cards decline on recurring billing; harder fraud & loyalty linking when one returning shopper uses a fresh card number on every order; in-store returns may not match the customer's physical tap.
    Issuer Far fewer costly plastic re-issuances and overnight mailings after merchant breaches; merchant-specific numbers help pinpoint which merchant suffered a leak. Must run high-availability number generation, virtual-to-primary account mapping, and token lifecycle controls; extra customer-support calls around declined subscriptions and disputed trial charges.

    Recommendation: Recommend virtual numbers for online one-off purchases, unfamiliar or small e-commerce sites, and free trials. Advise against single-use or short-lived virtual numbers when the physical card must be shown at fulfillment (hotels, car rentals, event pickup) or for critical recurring utilities (insurance, power, cloud hosting) unless a dedicated long-lived merchant-locked number is used and refund routing on closed virtual numbers is guaranteed.

  3. Part 2 · Evaluate R1, R2, and R3 on Card 1 through Card 5

    In Part 2 we evaluate every rule independently on all five inputs rather than stopping at the first failure. For R2 (Luhn), always index positions from the right starting at 0 so odd positions (1, 3, 5, ...) are doubled:

    16-digit layout (Card 1..4):
      left-to-right index:   0   1   2  ...  13  14  15
      from-the-right pos:   15  14  13  ...   2   1   0  (check digit)
      action:               x2  x1  x2  ...  x1  x2  x1
    
    15-digit layout (Card 5):
      from-the-right pos:   14  13  12  ...   2   1   0  (check digit)
      action:               x1  x2  x1  ...  x1  x2  x1  <-- leftmost digit is NOT doubled!
    

    Now compute each candidate's Luhn sum:

    Card 1 = "4242 4242 4242 4242" (16 digits, starts with '4')
      - Odd positions 1, 3, ..., 15: eight 4s doubled -> 8 * 8 = 64
      - Even positions 0, 2, ..., 14: eight 2s undoubled -> 8 * 2 = 16
      - Total = 64 + 16 = 80 -> 80 % 10 == 0 (R2 passes)
    
    Card 2 = "4242 4242 4242 4245" (16 digits, starts with '4')
      - Identical to Card 1 except position 0 (undoubled check digit) increases from 2 to 5 (+3)
      - Total = 80 + 3 = 83 -> 83 % 10 != 0 (R2 fails)
    
    Card 3 = "5600 0000 0000 0029" (16 digits, starts with '5')
      - Pos 15 ('5' doubled): 10 - 9 = 1; pos 14 ('6'): 6; pos 1 ('2' doubled): 4; pos 0 ('9'): 9
      - Total = 1 + 6 + 4 + 9 = 20 -> 20 % 10 == 0 (R2 passes)
    
    Card 4 = "3700 0000 0000 0007" (16 digits, starts with '3')
      - Pos 15 ('3' doubled): 6; pos 14 ('7'): 7; pos 0 ('7'): 7; zeros = 0
      - Total = 6 + 7 + 7 = 20 -> 20 % 10 == 0 (R2 passes, but R3 fails on '3')
    
    Card 5 = "5222 2222 2222 225" (15 digits, starts with '5')
      - Pos 14 ('5' undoubled): 5; six even-pos 2s: 12; seven odd-pos 2s doubled: 28; pos 0 ('5'): 5
      - Total = 5 + 12 + 28 + 5 = 50 -> 50 % 10 == 0 (R2 passes, but R1 fails on length 15)
    
    Label Normalized R1 (16 digits) R2 (Luhn) R3 (starts 4/5) Verdict
    Card 1 4242424242424242 Pass Pass (80) Pass (4) Accept
    Card 2 4242424242424245 Pass Fail (83) Pass (4) Reject (fails R2)
    Card 3 5600000000000029 Pass Pass (20) Pass (5) Accept
    Card 4 3700000000000007 Pass Pass (20) Fail (3) Reject (fails R3)
    Card 5 522222222222225 Fail (15 digits) Pass (50) Pass (5) Reject (fails R1)

    Only Card 1 and Card 3 meet all three rules.

  4. Part 3 · Trace why the buggy filter returns all five cards

    Look closely at the if statement in the buggy filter_cards:

    if len(number) == 16 or luhn_ok(number) and number[0] in "45":
        result.append(raw)
    

    In Python, and has higher operator precedence than or (just like multiplication binds tighter than addition), so Python groups that condition as:

    if (len(number) == 16)  OR  (luhn_ok(number) AND number[0] in "45"):
        ^----------------^       ^-----------------------------------^
        Branch 1: ANY 16-char    Branch 2: ANY non-16-char string that
        string passes at once!   passes luhn_ok AND starts with 4 or 5!
    

    Tracing all five sample inputs through those two branches:

    • Card 1, Card 2, Card 3, Card 4 all have len(number) == 16, so Branch 1 is True immediately! Because True or ... short-circuits, Python never even calls luhn_ok or checks the prefix on Card 2 or Card 4 — both invalid 16-digit cards sneak right in.
    • Card 5 has len(number) == 15 (False), so Python tries Branch 2: the buggy left-to-right luhn_ok("522222222222225") doubles indices 0, 2, ..., 14 (1 + 24 + 1 + 14 = 40, returning True), and "5" in "45" is True — so False or (True and True) evaluates to True, letting the 15-digit Card 5 sneak in too!

    As a result, the buggy function returns all five cards instead of just [Card 1, Card 3].

  5. Uncover the four hidden defects the sample test never reaches

    Fixing or to and alone still leaves four latent bugs waiting to crash or misclassify real-world inputs:

    1. len(number) == 16 ignores non-digits: "4242 4242 4242 424a" has length 16; the original code accepts it via len(number) == 16, and if you only change or to and, luhn_ok crashes with ValueError: invalid literal for int()!
    2. luhn_ok crashes on punctuation or letters: "4242-4242-4242-4242" has length 19, falls into luhn_ok, and raises ValueError on int("-").
    3. Empty or whitespace-only strings ("" or " ") crash with IndexError: number becomes "", luhn_ok("") loops zero times and returns 0 % 10 == 0 (True!), and number[0] raises IndexError: string index out of range.
    4. luhn_ok doubles from the left (i % 2 == 0) instead of from the right: on even lengths (16), left indices 0, 2, ..., 14 happen to match odd positions from the right (15, 13, ..., 1), hiding the bug! On odd lengths (such as a valid 15-digit Luhn number "400000000000006", whose right-to-left sum is 4 + 6 = 10), doubling from the left doubles both '4' (8) and '6' (12 - 9 = 3) for 11, falsely rejecting it.

    Focused unit tests that catch all five defects:

    def test_defect_1_all_three_rules_required():
        assert filter_cards(["4242424242424245", "3700000000000007", "522222222222225"]) == []
    
    
    def test_defect_2_sixteen_chars_with_letter():
        assert filter_cards(["4242 4242 4242 424a"]) == []
    
    
    def test_defect_3_hyphens_skipped_without_crash():
        assert filter_cards(["4242-4242-4242-4242"]) == []
    
    
    def test_defect_4_empty_and_blank_strings():
        assert filter_cards(["", "   "]) == []
        assert not luhn_ok("")
    
    
    def test_defect_5_odd_length_luhn_counts_from_right():
        assert luhn_ok("400000000000006")
        assert not luhn_ok("400000000000005")
    
  6. Build safe digit and right-to-left Luhn helpers

    First, write is_digit_string(text) using an explicit "0123456789" character check. Why avoid text.isdigit()? Because Python's .isdigit() returns True for Unicode superscripts like "²", which then crash int("²") with ValueError — and int() itself accepts full-width Unicode digits like "4" that payment rails reject!

    Next, make luhn_ok(number) self-contained: reject any non-digit or empty string up front, then iterate over enumerate(reversed(number)) so position == 0 is always the rightmost check digit and position % 2 == 1 always doubles every second digit from the right, regardless of string length.

    ASCII_DIGITS = "0123456789"
    
    
    def is_digit_string(text: str) -> bool:
        """Return True only for a non-empty string consisting strictly of ASCII digits 0-9."""
        if text == "":
            return False
        for ch in text:
            if ch not in ASCII_DIGITS:
                return False
        return True
    
    
    def luhn_ok(number: str) -> bool:
        """Validate a digit string of any length with the Luhn checksum; False if non-digits."""
        if not is_digit_string(number):
            return False
    
        total = 0
        for position, ch in enumerate(reversed(number)):
            digit_value = int(ch)
            if position % 2 == 1:
                digit_value *= 2
                if digit_value > 9:
                    digit_value -= 9
            total += digit_value
    
        return total % 10 == 0
    
  7. Evaluate each rule independently and combine with explicit `and`

    Putting R1, R2, and R3 in a small helper check_rules(raw) mirrors our Part 2 table directly (making debugging and logging trivial) and lets filter_cards require rules["R1"] and rules["R2"] and rules["R3"] with zero operator-precedence ambiguity.

    Watch two subtle Python traps in R3:

    • Slicing normalized[:1] safely returns "" on an empty string instead of raising IndexError like normalized[0].
    • Test membership against the tuple ("4", "5"), not the string "45", because "" in "45" evaluates to True in Python (the empty string is considered a substring of every string)!
    def check_rules(raw: str) -> Dict[str, bool]:
        """Evaluate R1 (16 digits), R2 (Luhn), and R3 (prefix 4 or 5) independently."""
        normalized = raw.replace(" ", "")
        return {
            "R1": len(normalized) == 16 and is_digit_string(normalized),
            "R2": luhn_ok(normalized),
            "R3": normalized[:1] in ("4", "5"),
        }
    
    
    def filter_cards(numbers: List[str]) -> List[str]:
        result = []
        for raw in numbers:
            rules = check_rules(raw)
            if rules["R1"] and rules["R2"] and rules["R3"]:
                result.append(raw)
        return result
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Restrict digits to ASCII '0'-'9': str.isdigit() accepts superscripts like '²' (which crash int()),
    # and int() accepts non-ASCII Unicode digits that card networks reject.
    ASCII_DIGITS = "0123456789"
    
    
    def is_digit_string(text: str) -> bool:
        """Return True only for a non-empty string consisting strictly of ASCII digits 0-9."""
        if text == "":
            return False
        for ch in text:
            if ch not in ASCII_DIGITS:
                return False
        return True
    
    
    def luhn_ok(number: str) -> bool:
        """Validate a digit string of any length with the Luhn checksum; False if non-digits."""
        # Guard malformed or empty strings so `luhn_ok` never raises ValueError or returns True on "".
        if not is_digit_string(number):
            return False
    
        total = 0
        # Reverse `number` so position 0 is always the rightmost check digit;
        # doubling odd positions (1, 3, 5, ...) works for both 16-digit and 15-digit cards.
        for position, ch in enumerate(reversed(number)):
            digit_value = int(ch)
            if position % 2 == 1:
                digit_value *= 2
                # For 10..18, subtracting 9 equals adding the two decimal digits (e.g., 14 -> 1+4 = 5).
                if digit_value > 9:
                    digit_value -= 9
            total += digit_value
    
        return total % 10 == 0
    
    
    def check_rules(raw: str) -> Dict[str, bool]:
        """Evaluate R1 (16 digits), R2 (Luhn), and R3 (prefix 4 or 5) independently."""
        # Strip spaces only; dashes, tabs, or letters remain in `normalized` and fail R1/R2 cleanly.
        normalized = raw.replace(" ", "")
        return {
            "R1": len(normalized) == 16 and is_digit_string(normalized),
            "R2": luhn_ok(normalized),
            # Slice `[:1]` avoids IndexError on "", and tuple `("4", "5")` avoids `"" in "45"` being True!
            "R3": normalized[:1] in ("4", "5"),
        }
    
    
    def filter_cards(numbers: List[str]) -> List[str]:
        # result: list of original `raw` card strings that satisfy R1 AND R2 AND R3, in input order
        result = []
        for raw in numbers:
            rules = check_rules(raw)
            if rules["R1"] and rules["R2"] and rules["R3"]:
                result.append(raw)
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a payment-card validator as a corridor with three security doors wired in series: a shape door (R1: exactly 16 ASCII digits 0–9), a math door (R2: the Luhn checksum, an error-detecting formula that weights alternating digits from right to left so single-digit typos fail to sum to a multiple of 10), and a network-prefix door (R3: begins with '4' or '5'). A virtual card number (a merchant-specific substitute card number linked to a customer's real account so leaks stay contained) should reach result only when all three doors open.

Why did the starter filter fail so badly? Instead of wiring all three checks in series with and, it wrote len(number) == 16 or luhn_ok(number) and number[0] in "45". Because of operator precedence (Python's rule that and binds tighter than or, grouping A or B and C as A or (B and C)) and short-circuit evaluation (stopping as soon as the left side of True or ... is True), the first check acted like an unlocked side door that let every 16-character string bypass Luhn and prefix checks completely! Worse, the code harbored latent defects (bugs hidden by the current sample inputs that fail on other valid test cases): unguarded int(ch) and number[0] calls crash on letters, hyphens, or blank strings, and luhn_ok counted indices from the left instead of from the rightmost check digit (the final digit chosen to make the total a multiple of 10), breaking odd-length card numbers.

Watch how three tricky inputs behave in the buggy code versus our fixed check_rules pipeline:

Raw input               Buggy filter                              Fixed check_rules -> Verdict
-----------------------------------------------------------------------------------------------
"4242 4242 4242 4245"   len == 16 is True -> KEPT (skips Luhn!)   R1=T, R2=F(sum 83), R3=T -> Reject
"5222 2222 2222 225"    len 15 -> False or (T and T) -> KEPT!     R1=F(len 15), R2=T, R3=T -> Reject
"   "                   len 0 -> luhn_ok("") is True -> CRASH!    R1=F, R2=F, R3=F         -> Reject

Complexity

Let n be the number of strings in numbers and L be the maximum character length of a single string.

  • Time: O(n * L). For each of the n strings, stripping spaces with replace(" ", ""), checking ASCII digits in is_digit_string, summing reversed digits in luhn_ok, and checking the 1-character slice normalized[:1] each scan the string a constant number of times (O(L) work per card).
  • Space: O(L) auxiliary space (plus up to O(n) references in result). Only one normalized copy normalized of length at most L is held in memory at a time, and result stores references to the accepted original input strings without duplicating their characters.

Edge cases

  • Empty input list []: returns [].
  • Empty string "" or spaces-only " ": normalized becomes ""; is_digit_string("") returns False, luhn_ok("") returns False, and ""[:1] in ("4", "5") returns False with no IndexError.
  • Arbitrary spacing (" 4242 4242 4242 4242 "): spaces anywhere are removed for validation, while the exact untouched raw string is appended to result.
  • Hyphens, tabs, newlines, or letters ("4242-4242-4242-4242", "4242 4242 4242 424a"): non-space separators and letters remain in normalized, so is_digit_string cleanly rejects them without raising ValueError.
  • Unicode digit lookalikes ("²", full-width "4"): rejected because ASCII_DIGITS only permits ASCII '0'–'9', avoiding str.isdigit() / int() mismatches.
  • 15- or 17-digit numbers that pass Luhn and start with '4' or '5': R2 and R3 are True, but R1 is False, so they are rejected.
  • Duplicate valid entries: preserved in exact input order each time they appear.

Common mistakes

  • Mixing or and and without parentheses: len == 16 or luhn and prefix parses as len == 16 or (luhn and prefix). Combining named rule flags with and only (rules["R1"] and rules["R2"] and rules["R3"]) makes precedence bugs impossible.
  • Counting Luhn positions from the left (i % 2 == 0): works by coincidence on 16-digit strings (even length) because index 0 is position 15 from the right, but doubles the wrong digits on 15-digit cards (such as American Express) or 13/19-digit cards. Always count from the right with reversed(number).
  • Doubling even positions from the right (position % 2 == 0): accidentally doubles the rightmost check digit instead of every second digit to its left, rejecting valid cards like Card 1.
  • Using digit_value % 9 instead of if digit_value > 9: digit_value -= 9: when '9' is doubled to 18, subtracting 9 gives 1 + 8 = 9, whereas 18 % 9 wrongly gives 0!
  • Writing normalized[:1] in "45": when normalized is "", normalized[:1] is "", and "" in "45" is True because the empty string is a substring of every string! Always check membership in a tuple ("4", "5").
  • Returning normalized instead of raw: strips the caller's formatting spaces and fails tests that expect the original strings back.

Follow-up questions

  • What classes of data-entry typos are guaranteed to fail the Luhn algorithm, and which transposition mistakes escape detection? Luhn always catches every single-digit substitution error (typing one wrong digit), because both the x1 map (0..9 -> 0..9) and the x2 (minus 9 if > 9) map (0..9 -> 0, 2, 4, 6, 8, 1, 3, 5, 7, 9) are one-to-one permutations of 0..9, so changing one digit always changes the sum modulo 10. It also catches every adjacent two-digit transposition (ab -> ba, where one position is doubled and its neighbor is not) except 09 <-> 90, because (2*0) + 9 = 9 equals (2*9 - 9) + 0 = 9! However, Luhn never catches jump transpositions two places apart (abc -> cba) because positions i and i + 2 receive identical weights, and it misses symmetric twin errors like 22 <-> 55, 33 <-> 66, and 44 <-> 77.
  • How would you refactor the validator to support 15-digit cards or additional network prefixes without editing boolean logic each time? Replace hardcoded constants with a data-driven schema table — for example, a list of network specs [CardSpec(prefixes=("4",), lengths={16}), CardSpec(prefixes=("5",), lengths={16}), CardSpec(prefixes=("34", "37"), lengths={15})]. Validation then loops over the configured specs (checking longest prefixes first if specs can overlap) to see whether normalized.startswith(spec.prefixes) and len(normalized) in spec.lengths, followed by luhn_ok(normalized). Because our fixed luhn_ok already counts positions from the right using reversed(number), adding 15-digit or 19-digit card programs requires zero code changes to the checksum function.
  • How could you use automated input generation to test the validator beyond manually chosen test cases? Use property-based testing — an automated testing technique (popularized in Python by the Hypothesis library) that generates hundreds of random inputs satisfying known mathematical invariants instead of relying only on hand-written constants. For example, generate random prefix + body digits, compute the unique Luhn check digit ((10 - partial_sum % 10) % 10), and verify that: (1) valid 16-digit 4/5 numbers always pass even after inserting random spaces, (2) mutating any single digit in a valid card always causes rejection, (3) injecting any non-digit character never raises an exception, and (4) filter_cards matches an independent regex + weight-table reference implementation.
  • At which system boundaries—browser/app UI, checkout backend, or issuer authorization service—should card validation execute? Run validation across all three layers, each serving a distinct purpose. Running format and Luhn checks in the browser or mobile UI gives shoppers immediate typo feedback with zero network round-trip, though client checks are trivial for a script or API caller to bypass. Repeating those checks in the checkout backend blocks malformed payloads cheaply before incurring external network latency or per-request gateway fees. Finally, the issuer's authorization service is the true source of authority: beyond format and checksum sanity, only the issuer can confirm that the virtual card number exists, remains active, satisfies merchant/spend controls, and maps to a funded account.

Follow-up questions

Similar questions

More Capital One interview questions

All 268 Capital One questions →