# Luhn Algorithm question

Hi,

I have a task where i need to use luhn algorithm to check credit cards are valid, and if they are the box goes green, if they are not the box goes red. I’ve found the below javascript on GitHub that looks to do what i need, but i am unsure on how to add the code to make the boxes change colour. I believe i need an if/ else statement but i’m not sure how to implement it. I was thinking something like this as the code for the colour change:

document.getElementById(‘cardInput’).style.backgroundColor = “green”;

Here is the JS i found on GitHub:

function cardnumber(value) {
if (/[^0-9-\s]+/.test(value))
return false;
let nCheck = 0, bEven = false;
value = value.replace(/\D/g, “”);
for (var n = value.length - 1; n >= 0; n–) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven && (nDigit *= 2) > 9) nDigit -= 9;
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}

and here is my html line relating to the card input:

``````<li>Card:<input id="cardInput" onkeyup="cardnumber(this)" type='text' name='card' placeholder="Enter a Proxy Credit Card Number."/></li>
``````

Any help would be great

Thanks!

Hi I’m a fellow learner so i may not solve your problem but I’ll try to understand.

1. Basically the `function cardnumber(value){}` returns boolean either false or true.

2. Assuming that false means invalid CC and true means valid CC. Create a If-else statement like this: (after you state the function)

``````if(cardnumber(insertCreditCardNumberHere)){
/* do things when CC is valid */
document.getElementById(‘cardInput’).style.backgroundColor = “green”;
}
else{
/* do things when CC is invalid */
document.getElementById(‘cardInput’).style.backgroundColor = “red”;
}
``````

Hope this can helps !

You could do something like the following. Note I changed the `onkeyup` function name that is called.

``````<li>Card:<input id="cardInput" onkeyup="checkCard(this)" type='text' name='card' placeholder="Enter a Proxy Credit Card Number."/></li>
``````
``````function isValidCC(cardNumber) {
if (/[^0-9-\s]+/.test(cardNumber)) return false;
let nCheck = 0, bEven = false;
cardNumber = cardNumber.replace(/\D/g, '');
for (let n = cardNumber.length - 1; n >= 0; n--) {
const cDigit = cardNumber.charAt(n);
let nDigit = parseInt(cDigit, 10);
if (bEven && (nDigit *= 2) > 9) nDigit -= 9;
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) === 0
}

function checkCard(cardInput) {
const color = isValidCC(cardInput.value) ? 'green' : 'red';
cardInput.style.backgroundColor = color;
}
``````

Thank you! That is exactly what I needed and my task now works! Thanks!

Thank you, that’s the sort of method I had been trying but I couldn’t get it to work. The solution below seems to fix my problem but thank you for your help!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.