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:
- 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.
- Sum all digits in the altered number.
- 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 == 0Code
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 trueCreate A Luhn Algorithm Validator
- A user enters a credit card in your form
- If the Luhn Algorithm says its valid, show a message that the card is valid
- If the Luhn Algorith says its invalid show a message that it is not valid
- The Luhn Algo should be checking every time the state changes using the useEffect hook
Steps to creating the Luhn Algorithm Validator
- Create a React project using Create React App.
- Create a form that includes an input field for the user to enter the credit card number.
- Use some javascript i.e a regular expression, to validate that the input value is a valid credit card number (16 digits all numbers).
- 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.
- 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.
- Add styling to your application to make it look professional and user-friendly.