Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Last active October 31, 2021 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coolaj86/bce6a5fc03b4786a363435b176a19765 to your computer and use it in GitHub Desktop.
Save coolaj86/bce6a5fc03b4786a363435b176a19765 to your computer and use it in GitHub Desktop.
How to Format a (Visa) Credit Card input
var CC = {};
window.CC = CC;
(function () {
"use strict";
// 4242-4242-4242-4242
function formatVisa(digits, pos) {
var all = "";
all += digits.slice(0, 4);
if (all.length < 4) {
return [all, pos];
}
if (pos >= all.length) {
pos += 1;
}
all += "-";
all += digits.slice(4, 8);
if (all.length < 9) {
return [all, pos];
}
if (pos >= all.length) {
pos += 1;
}
all += "-";
all += digits.slice(8, 12);
if (all.length < 14) {
return [all, pos];
}
if (pos >= all.length) {
pos += 1;
}
all += "-";
all += digits.slice(12);
return [all, pos];
}
// 37xx-654321-54321
function formatAmex(digits, pos) {
var all = "";
all += digits.slice(0, 4);
if (all.length < 4) {
return [all, pos];
}
if (pos >= all.length) {
pos += 1;
}
all += "-";
all += digits.slice(4, 10);
if (all.length < 11) {
return [all, pos];
}
if (pos >= all.length) {
pos += 1;
}
all += "-";
all += digits.slice(10);
return [all, pos];
}
CC.formatCardDigits = function (ev) {
// TODO handle backspace
var $cc = ev.target;
var digits = "";
var pos = $cc.selectionStart;
// us: 4242-4242-42|
// em: 4242-424|2-42 // 8
// em: 4242-4244|2-42 // 9
// us: 4242-4244-|242 // 10
// ex: 4242-|4244-242 // 10
// check the character before the cursor
// (ostensibly the character that was just typed)
// assuming a left-to-right writing system
// 4242-|
if (!/[0-9]/.test(ev.key)) {
return;
}
// rework position
var j = pos;
var i;
for (i = 0; i < $cc.value.length; i += 1) {
if ($cc.value[i].match(/[0-9]/)) {
digits += $cc.value[i];
continue;
}
if (i < j) {
pos -= 1;
}
}
// https://stevemorse.org/ssn/List_of_Bank_Identification_Numbers.html
var reVisa = /^4/;
var reMastercard = /^5[1-5]/;
var reAmex = /^37/;
var parts;
if (reAmex.test(digits)) {
parts = formatAmex(digits, pos);
} else {
parts = formatVisa(digits, pos);
}
$cc.value = parts[0];
$cc.selectionStart = parts[1];
$cc.selectionEnd = $cc.selectionStart;
};
CC.pay = function (ev) {
var $payForm = ev.target;
var digits = CC.formatCardDigits(
$payForm.querySelector('[name="cc-digits"]').value
);
var mm = $payForm.querySelector('[name="cc-mm"]').value;
var yyyy = $payForm.querySelector('[name="cc-yyyy"]').value;
var code = $payForm.querySelector('[name="cc-code"]').value;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment