Format and Validate a Card Number Field as the Buyer Types
Last updated: November 29, 2026
Quick Overview
Write the logic behind a hosted card input: strip non-digits, detect the brand from the leading digits, group the digits for display by brand, and report whether the number is complete and passes the Luhn check.
Square
November 29, 20260
0
0 solved
Write the logic behind a hosted card input: strip non-digits, detect the brand from the leading digits, group the digits for display by brand, and report whether the number is complete and passes the Luhn check.
Square's Web Payments SDK renders a card form inside the seller's checkout page, and the field's live formatting is something every buyer touches. The interviewer checks a correct Luhn implementation, clean brand rules, and awareness of input UX details like pasted text and caret position.
What the Interviewer Expects
- Implement Luhn correctly from the rightmost digit
- Detect at least Visa, Mastercard (including 2-series) and Amex
- Group digits per brand (Amex 4-6-5)
- Distinguish incomplete from invalid
- Mention caret handling and paste in the real UI
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How do you keep the caret in the right place when a space is inserted before it?
- How would you load brand ranges from a config rather than code?
- Why should the server still validate even though the client does?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: whatever the buyer typed or pasted. Output: brand, display string, complete (length valid for brand), valid (complete and Luhn passes). Unknown brands get a default 16-digit grouping. Never...
High-Level Design
Keep brand rules as data: a predicate on the prefix, the allowed lengths and the display groups. Normalize to digits, pick the first matching brand, truncate to its maximum length, slice into groups, ...