Step 13
Here is the completed Luhn algorithm:
const cnumber = "4003600000000014"; let arr = cnumber .split('') .reverse() .map(element => parseInt(element)); const sum = arr.reduce(reducer, 0) function reducer(accumulator, currentValue, currentIndex) { currentIndex += 1; // account for 0-based indexing if (currentIndex % 2 === 0) { // even index currentValue *= 2; if (currentValue > 9) { currentValue -= 9; } } return accumulator + currentValue; } if (sum % 10 === 0) { console.log("Valid card number"); } else { console.log("Invalid card number"); }
You can try the above for another valid input, 6011329933655299
.
Here is the final script.js
:
const submitBtn = document.getElementById("submit");
submitBtn.addEventListener("click", handleFormSubmit);
function handleFormSubmit(event) {
event.preventDefault();
const month = document.getElementById("month").value;
const year = document.getElementById("year").value;
if (new Date() > new Date(year, month)) {
window.alert("Your card is expired!");
return;
}
const cvv = document.getElementById("cvv").value;
if (!/^[0-9]{3,4}$/.test(cvv)) {
window.alert("Invalid CVV. It must be 3 or 4 digits!");
return;
}
const cnumber = document.getElementById("cnumber").value;
if (!/^[0-9]{13,16}$/.test(cnumber) || !isValid(cnumber)) {
window.alert("Invalid card number!");
return;
}
window.alert("Thanks for the payment!");
}
function isValid(cnumber) {
let arr = cnumber
.split("")
.reverse()
.map((element) => parseInt(element));
const sum = arr.reduce(reducer, 0);
function reducer(accumulator, currentValue, currentIndex) {
currentIndex += 1; // account for 0-based indexing
if (currentIndex % 2 === 0) {
// even index
currentValue *= 2;
if (currentValue > 9) {
currentValue -= 9;
}
}
return accumulator + currentValue;
}
return sum % 10 === 0;
}
Notice the regular expression to ensure entered card number is a numerical input with 13 to 16 digits. Moreover, the reducer
function is defined inside isValid
. In JavaScript, you can declare a function inside another one!
Here is the payment form in action: