Format Card Take 4

by TokenEx Support

HTML

<input type="text" id="data" maxlength="25" />

JavaScript

data = document.getElementById("data");
//addEventListener(data, "keypress", limitNumericInput);
//addEventListener(data, "keypress", formatCreditCard);
//addEventListener(data, "keydown", handleBackSpace);
addEventListener(data, "paste", reFormatCreditCard);
addEventListener(data, "input", reFormatCreditCard);
addEventListener(data, "change", reFormatCreditCard);


function reFormatCreditCard(e) {
  console.log("reFormatCreditCard");
  var target = e.currentTarget;
  var value = target.value;
  value = formatWholeCreditCard(value);
  return safeVal(value, target);
}

function formatWholeCreditCard(num) {
  num = num.replace(/\D/g, '');
  var card = getPossibleCardType(num);
  if (!card) {
    return num.substring(0, 19);
    
  }
  //strip any characters over the maxLength
  /*num = num.slice(0, card.maxLength);
  var groups = card.format.exec(num);
  if (groups == null) {
    return num;
  }
  groups.shift();
  return groups.join(' ')
  */
  num = num.substring(0, card.maxLength);
  var chunks = [];
  chunks.push(num.substring(0, 4));
  if (card.type === "amex") {
    if (num.length >= 5) {
      chunks.push(num.substring(4, 10));
    }
    if (num.length >= 11) {
      chunks.push(num.substring(10, 15));
    }
  } else {
    if (num.length >= 5) {
      chunks.push(num.substring(4, 8));
    }
    if (num.length >= 9) {
      chunks.push(num.substring(8, 12));
    }
    if (num.length >= 13) {
      chunks.push(num.substring(12, 16));
    }
  }
  return chunks.join(" ")
}

function handleBackSpace(e) {
  //if it's not a backspace then bounce out
  if (e.which !== 8) {
    return;
  }
  console.log("handleBackSpace");
  var target, value;
  target = e.currentTarget;
  value = target.value;
  var cursorPos = target.selectionStart;
  //if it's a backspace in the middle of the value
  if (cursorPos != null && cursorPos !== value.length) {
    return;
  }
  //if it's a backspace at the end of the value and the value is number + space ex: '5 '
  if...