How to validate a credit card number with JavaScript?

Sometimes, we want to validate a credit card number with JavaScript.

In this article, we’ll look at how to validate a credit card number with JavaScript.

How to validate a credit card number with JavaScript?

To validate a credit card number with JavaScript, we can use the Lyhn algorithm.

For instance, we write:

const checkLuhn = (cardNo) => {
  let s = 0;
  let doubleDigit = false;
  for (const d of [...cardNo].reverse()) {
    let digit = +d;
    if (doubleDigit) {
      digit *= 2;
      if (digit > 9)
        digit -= 9;
    }
    s += digit;
    doubleDigit = !doubleDigit;
  }
  return s % 10 === 0;
}

console.log(checkLuhn('4242424242424242'))
console.log(checkLuhn('8242424242424242'))

to define the checkLuhn function that uses the Luhn algorithm to check if cardNo is a credit card number.

The steps in the algorithm are:

  1. If the number already contains the check digit, drop that digit to form the “payload.” The check digit is most often the last digit.
  2. With the payload, start from the rightmost digit. Moving left, double the value of every second digit (including the rightmost digit).
  3. Sum the digits of the resulting value in each position.
  4. Sum the resulting values from all position s.

Steps 2 to 4 are done with

for (const d of [...cardNo].reverse()) {
  let digit = +d;
  if (doubleDigit) {
    digit *= 2;
    if (digit > 9)
      digit -= 9;
  }
  s += digit;
  doubleDigit = !doubleDigit;
}
  1. The check digit is calculated by s % 10 === 0.

Therefore, the first console log logs true and the 2nd logs false.

Conclusion

To validate a credit card number with JavaScript, we can use the Lyhn algorithm.