The Luhn Algorithm

The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers and National Provider Identifier (NPI) numbers. It can also be used to validate a variety of other account identification numbers.

Credit card numbers can be validated with the Luhn algorithm. To use the Luhn algorithm to verify credit card numbers, it works like this:

  1. Starting with the next to last digit and continuing with every other digit going back to the beginning of the card number, double the digit.
  2. Sum all digits in the altered number.
  3. If that total is a multiple of 10, the number is valid.

For example, given the card number 4408 0412 3456 7893:

Orig  :  4 4 0 8 0 4 1 2 3 4   5 6   7 8   9 3
Step 1:  8 4 0 8 0 4 2 2 6 4  10 6  14 8  18 3
Step 2:  8+4+0+8+0+4+2+2+6+4+1+0+6+1+4+8+1+8+3 = 70
Step 3:  70 % 10 == 0

Luhn Algorithm

Code

Write a function validCard that takes a number as an argument and returns true for a valid number and false for an invalid number.

validCard(1234567890123456); //should be false
validCard(4408041234567893); //should be true
validCard(38520000023237); //should be true
validCard(4222222222222); //should be true

Create A Luhn Algorithm Validator

  1. A user enters a credit card in your form
  2. If the Luhn Algorithm says its valid, show a message that the card is valid
  3. If the Luhn Algorith says its invalid show a message that it is not valid
  4. The Luhn Algo should be checking every time the state changes using the useEffect hook

Steps to creating the Luhn Algorithm Validator

  1. Create a React project using Create React App.
  2. Create a form that includes an input field for the user to enter the credit card number.
  3. Use some javascript i.e a regular expression, to validate that the input value is a valid credit card number (16 digits all numbers).
  4. Implement the Luhn Algorithm to check if the credit card number is valid or not, and display an appropriate validation message depending on the result.
  5. Create a Submit button that when clicked, will validate the credit card number and display an appropriate message depending on whether it is valid or not.
  6. Add styling to your application to make it look professional and user-friendly.