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...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.