Lesson 7 of 8 · 15 min

Challenge: Catch typos with the Luhn check

Nisha is building a top-up form for a mobile money app in Port Louis. People type long card numbers on small phone keyboards, and they make mistakes. Before sending anything to the bank, she wants to catch the typos.

Luckily, card numbers carry a built-in safety check. The last digit is a check digit, chosen so that the whole number passes the Luhn check:

  1. Starting from the rightmost digit, leave it as it is, double the next one, leave the next, double the next, and so on.
  2. If doubling gives a number above 9, take 9 off it (so 7 doubled is 14, which becomes 5).
  3. Add up all the digits after step 2.
  4. If the total ends in 0 (total % 10 === 0), the number is valid.

For 79927398713:

digits:   7  9  9  2  7  3  9  8  7  1  3
double?     x2    x2    x2    x2    x2
becomes:  7 18  9  4  7  6  9 16  7  2  3
-9 if >9: 7  9  9  4  7  6  9  7  7  2  3   total 70, valid!

Change any single digit and the total no longer ends in 0, so the typo is caught.

Your task

Write two functions:

  1. isValidCard(number) takes the number as text and returns true if it passes the Luhn check, otherwise false.
  2. checkDigit(partial) takes a number without its last digit and returns the check digit (a number from 0 to 9) that makes it valid.
isValidCard("79927398713")            // true
isValidCard("4539 3195 0343 6467")    // true   (spaces are fine)
isValidCard("79927398710")            // false  (a typo)
isValidCard("055-444-285")            // false  (only digits and spaces allowed)
isValidCard("0")                      // false  (too short)

checkDigit("7992739871")              // 3

Rules

  • Spaces are allowed anywhere and are ignored.
  • Any other character that is not a digit makes the number invalid.
  • After removing spaces, a number needs at least 2 digits to be valid.
  • checkDigit gets digits only (no spaces) and returns a number, not text.

Tips

  • number.replaceAll(" ", "") removes the spaces.
  • A character is a digit when ch >= "0" && ch <= "9", and Number(ch) turns it into a number.
  • Loop from the end: for (let i = digits.length - 1; i >= 0; i--), and keep a true/false flag that flips each time to know whether to double.
  • For checkDigit, you already have a working isValidCard. Try all ten possible endings!
main.js
function isValidCard(number) {
  // TODO: remove spaces, check the characters, then do the Luhn sum
  return false;
}

function checkDigit(partial) {
  // TODO: find the digit 0-9 that makes partial valid
  return 0;
}

console.log(isValidCard("4539 3195 0343 6467"));  // should print true
console.log(checkDigit("7992739871"));            // should print 3

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…