10. Validate a Card Number at Checkout

EasyJavaScriptPayments

On the checkout payment form, the card brand logo appears while the shopper types, and obvious typos are caught before the request goes to the payment provider. Every failed request costs money and can trigger fraud checks.

Card numbers carry a built-in checksum (the Luhn algorithm) plus brand-specific prefixes and lengths. Shoppers often paste numbers with spaces or dashes.

Your task: - luhnCheck(digits): true when a string of digits passes the Luhn checksum. - detectBrand(digits): "visa", "mastercard", "amex" or "unknown", from the prefix only. - checkCardNumber(input): returns { valid, brand } for what the shopper typed, using the two functions above.

Luhn checksum: - Starting from the rightmost digit and moving left, double every second digit (the 2nd, 4th, ... from the right). If doubling gives more than 9, subtract 9. - Add up all the digits. The number passes when the sum is divisible by 10.

Brands: - visa: starts with 4. Allowed lengths 13, 16 or 19. - mastercard: starts with 51 to 55, or 2221 to 2720. Length 16. - amex: starts with 34 or 37. Length 15. - Anything else is "unknown".

Rules for checkCardNumber: - Remove spaces and dashes first. Any other non-digit character gives { valid: false, brand: "unknown" }. - The brand is reported from the prefix even when the length or checksum is wrong, so the logo shows while typing. - valid is true only when the brand is known, the length is allowed for that brand and the Luhn check passes.

Notes: - The tests only use the public test numbers published by payment providers.

What you'll write

  • luhnCheckfunctionLuhn checksum for a string of digits.
  • detectBrandfunctionThe brand from the prefix of a string of digits.
  • checkCardNumberfunctionCleans the input and combines the two checks.

Each one has its own test cases, and the last one is also tested together with the others. Implement them in order.

Examples

Example 1

Function
checkCardNumber
Input
  • input = "4242 4242 4242 4242"
Output
  • { valid: true, brand: "visa" }
Explanation
Starts with 4, has 16 digits and passes the Luhn check.

Example 2

Function
checkCardNumber
Input
  • input = "4242 4242 4242 4241"
Output
  • { valid: false, brand: "visa" }
Explanation
A typo in the last digit breaks the checksum, but the brand is still shown.

Solution

Write luhnCheck, detectBrand and checkCardNumber. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.

Test Results

Click "Run Code" to test your solution.