Created
July 5, 2018 15:04
-
-
Save atomkirk/97dcdf8c57af78f2e3331395efaf57ac to your computer and use it in GitHub Desktop.
credit card formatter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const blocks = { | |
uatp: [4, 5, 6], | |
amex: [4, 6, 5], | |
diners: [4, 6, 4], | |
discover: [4, 4, 4, 4], | |
mastercard: [4, 4, 4, 4], | |
dankort: [4, 4, 4, 4], | |
instapayment: [4, 4, 4, 4], | |
jcb15: [4, 6, 5], | |
jcb: [4, 4, 4, 4], | |
maestro: [4, 4, 4, 4], | |
visa: [4, 4, 4, 4], | |
mir: [4, 4, 4, 4], | |
unionPay: [4, 4, 4, 4], | |
general: [4, 4, 4, 4], | |
generalStrict: [4, 4, 4, 7] | |
} | |
const patterns = { | |
// starts with 1; 15 digits, not starts with 1800 (jcb card) | |
uatp: /^(?!1800)1\d{0,14}/, | |
// starts with 34/37; 15 digits | |
amex: /^3[47]\d{0,13}/, | |
// starts with 6011/65/644-649; 16 digits | |
discover: /^(?:6011|65\d{0,2}|64[4-9]\d?)\d{0,12}/, | |
// starts with 300-305/309 or 36/38/39; 14 digits | |
diners: /^3(?:0([0-5]|9)|[689]\d?)\d{0,11}/, | |
// starts with 51-55/2221–2720; 16 digits | |
mastercard: /^(5[1-5]\d{0,2}|22[2-9]\d{0,1}|2[3-7]\d{0,2})\d{0,12}/, | |
// starts with 5019/4175/4571; 16 digits | |
dankort: /^(5019|4175|4571)\d{0,12}/, | |
// starts with 637-639; 16 digits | |
instapayment: /^63[7-9]\d{0,13}/, | |
// starts with 2131/1800; 15 digits | |
jcb15: /^(?:2131|1800)\d{0,11}/, | |
// starts with 2131/1800/35; 16 digits | |
jcb: /^(?:35\d{0,2})\d{0,12}/, | |
// starts with 50/56-58/6304/67; 16 digits | |
maestro: /^(?:5[0678]\d{0,2}|6304|67\d{0,2})\d{0,12}/, | |
// starts with 22; 16 digits | |
mir: /^220[0-4]\d{0,12}/, | |
// starts with 4; 16 digits | |
visa: /^4\d{0,15}/, | |
// starts with 62; 16 digits | |
unionPay: /^62\d{0,14}/ | |
} | |
export default function formatCc(value) { | |
var block | |
for (var key in patterns) { | |
if (patterns[key].test(value)) { | |
block = blocks[key] | |
} | |
} | |
if (!block) { | |
return value | |
} | |
let result = '' | |
let currentDelimiter = ' ' | |
block.forEach((length, index) => { | |
if (value.length > 0) { | |
let sub = value.slice(0, length) | |
let rest = value.slice(length) | |
result += sub | |
if (sub.length === length && index < block.length - 1) { | |
result += currentDelimiter | |
} | |
// update remaining string | |
value = rest | |
} | |
}) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment