crdit card input format code example

Example: crdit card input format

var myInput = document.querySelector("#myInput");
myInput.addEventListener("input", updateFunpassInputCode);
function updateInputCode(e) {
    var cardNumber = myInput.value;

	  // Do not allow users to write invalid characters
    var formattedCardNumber = cardNumber.replace(/[^\d]/g, "");
    var formattedCardNumber = formattedCardNumber.substring(0, 12);

    // Split the card number is groups of 4
    var cardNumberSections = formattedCardNumber.match(/\d{1,4}/g);
    if (cardNumberSections !== null) {
        formattedCardNumber = cardNumberSections.join('-');
    }

    // If the formmattedCardNumber is different to what is shown, change the value
    if (cardNumber !== formattedCardNumber) {
        myInput.value = formattedCardNumber;
    }
}

Tags:

Misc Example