I am currently trying to learn to become a web developer and have a task where I need to use luhn algorithm to check credit cards are valid. If they are valid 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 color change:
document.getElementById(‘cardInput’).style.backgroundColor = “green”;
Here is my html:
<form name="form1" action="#">
<ul>
<li>Name:<input id="nameInput" onkeyup="letterscheck(this)" type='text' name='name' placeholder="Enter Your Name"/></li>
<li>Email:<input id="emailInput" onkeyup="emailcheck(this)" type='text' name='email'placeholder="Enter Your Email"/></li>
<li>Card:<input id="cardInput" onkeyup="cardnumber(this)" type='text' name='card' placeholder="Enter a Proxy Credit Card Number."/></li>
<li class="submit"><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</div>
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;
}
My JS for the other 2 fields
function letterscheck(inputtxt)
{
var namechecker = /^[a-zA-Z]+(?:[\s.]+[a-zA-Z]+)*$/;
if(inputtxt.value.match(namechecker))
{
document.getElementById('nameInput').style.backgroundColor = "green";
return true;
}
else
{
document.getElementById('nameInput').style.backgroundColor = "red";;
return false;
}
}
function emailcheck(inputtxt)
{
var emailchecker = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(inputtxt.value.match(emailchecker))
{
document.getElementById('emailInput').style.backgroundColor = "green";
return true;
}
else
{
document.getElementById('emailInput').style.backgroundColor = "red";
return false;
}
}
Hopefully, this is a really easy one for you all! Any help would be great.
Thanks!