Luhn Algorithm Implementation into original code

99 Views Asked by At

<!DOCTYPE html>
<html <head>
<meta charset="utf-8">
<title>Credit Card Number Validator</title>
<style>
  <!-- .title {
    font-family: "Trebuchet MS";
    font-size: 30px;
    font-style: oblique;
    color: #006600;
    text-align: center;
  }
  
  body {
    background-color: #FFFFE8;
    font-family: Arial, Helvetica, sans-serif;
  }
  
  table {
    margin: auto;
    width: 600px;
  }
  
  .right {
    text-align: right;
  }
  
  .center {
    text-align: center;
  }
  
  #id {
    width: 175px;
  }
  
  -->
</style>
</head>

<body>
  <p class="title">Validate a credit card number </p>
  <form name="form1" id="form1" method="post" action="">
    <table>
      <tr>
        <td width="219" class="right">Enter the credit card number:</td>
        <td width="168" class="center"><input name="textfield" type="text" id="card"></td>
        <td width="196" id="output">&nbsp;</td>
      </tr>
      <tr>
        <td height="30">&nbsp;</td>
        <td class="center"><input type="button" id="button" value="Test the Card Number!"></td>
        <td>&nbsp;</td>
      </tr>
    </table>
  </form>
  <script>
    document.getElementById("button").addEventListener('click', credit, false);

    function credit() {
      data = document.getElementById("card").value;
      if (data) {
        cardnum = data.replace(/[^0-9]/, "");
      } else {
        alert('Please enter a number to test.');
      }
      if (cardnum.length == 16 && cardnum.charAt(0) == "5" && cardnum.charAt(1) != "0" && cardnum.charAt(12) == "7") {
        donecard = +cardnum.substr(0, 3) + " ";
        document.getElementById("card").innerHTML = donecard;
        document.getElementById("output").innerHTML = "valid";
      } else {
        document.getElementById("output").innerHTML = "invalid";
      }
    }
  </script>
</body>

</html>

I'm trying to implement the Luhn algorithm to my code, so that it works together. My first block works well it validates numbers correctly based off the code. This block works correctly. I want to implement the second part to it, which is the luhn algorithim with a loop or loops. What would be the best way to do this.

1

There are 1 best solutions below

1
On

Something like this might work. Typed from my phone so probably has typos.

let sum = 0;
let len = cardnum.length;
for(let i=0; i = len; i++) { 
    let foo = cardnum.charAt(len-i) 
    if(i % 2 ) {
        foo = foo * 2;
        foo = (foo) > 9) ? foo-9 : foo;
        sum = sum + foo;
    } else {
        sum = sum + foo
}
if( (sum * 9) % 10 === 0) {
    console.log(‘valid’)
}