Search code examples
javascripthtmlcolorsbackgroundluhn

Changing textbox background color upon clicking out


I'm trying to get the textbox background color to change on clicking out to rgb(137,200,46) if the input is correct and to rgb(B 231,0,100) if it's not, otherwise to stay white. The incorrect color shows up alright upon a wrong sequence, but I keep getting green even if the textbox is empty, instead of pink (since an empty textbox is incorrect, for this task). As an example, a correct input would be "79927398713" and I'm just typing "123" or leaving it empty to get an incorrect one. I tried both values !== "" and values !== 0, each as a && in the first if and as an added if else. I tried the same things with box and integers, but at this point I'm just grasping at straws. Could you please tell me where I'm going wrong? Please go easy on me, I'm still very rgb(137,200,46).

function checkLuhn(array) {
  let nDigits = array.length;
  let nSum = 0;
  let isSecond = false;
  for (let i = nDigits - 1; i >= 0; i--) {
    let d = array[i] - '0';
    if (isSecond == true)
      d = d * 2;

    nSum += parseInt(d / 10, 10);
    nSum += d % 10;
    isSecond = !isSecond;
  }
  return (nSum % 10 == 0);
}

function verify() {
  var box = document.getElementById("cardBox");
  const values = box.value.split("");
  const integers = values.map((value) => parseInt(value.trim(), 10));
  if ((checkLuhn(integers)) && (values !== ""))
  {
    box.style.background = "rgb(137,200,46)";
  } else
  {
    box.style.background = "rgb(231,0,100)";
  }
}
<!--Debit/Credit Card input; I set the type to password as an added layer of security-->
<label for="card" data-mlr-text>Card</label>
<input type="password" id="cardBox" placeholder="Write your Credit/Debit Card here" title="Write your Credit/Debit Card number" pattern="\d{10,19}" required onfocusout=verify()>


Solution

  • It looks like you are trying to check array with string. values !== "" Where values is array, so this will be always true.

    You need to check box.value !== “” or better !box.value