I am trying to format credit cards as users type them into the field. I've read every topic on the subject here on stack overflow, looked at tons of sites, lots of libraries and the code behind them. I want to create a simple function that will format credit cards as the user types them into the field using VANILLA JAVASCRIPT. Some of the following code comes from topics found here on Stack Overflow but none of the threads have solved the particular problem of doing this as the user is typing into the field.
PROBLEM: By default as the user is typing the into the given credit card field it changes the value by putting spaces in between the numbers, it will not validate as an American Express card until all the digits have been entered and thus not adjust the format until it is complete. I've tried casting the value without spaces and retesting it every cycle but to no avail.
function cc_format(v) {
//Strip the field value of spaces.
amextest = v.replace(/\s/g, '');
//Test if the card is an american express each cycle
if(/3[47]\d{2}[ -]*\d{6}[ -]*\d{5}/.test(amextest))
{
//This is some borrowed code to format american express cards - http://stackoverflow.com/questions/27322733/javascript-regex-format-string-containing-american-express-card-number
v.replace(/\b(\d{4})(\d{6})(\d{5})\b/, '$1-$2-$3');
return v;
}
else
{
//This properly formats every other card type as its being typed.
var v = v.replace(/[^\d]/g, '').match(/.{1,4}/g);
return v ? v.join(' ') : '';
}
}
//This binds the function to an input
document.getElementById('credit_card').oninput = function() {
this.value = cc_format(this.value)
}
I call upon the gods of stack overflow, please help me put this rest once and for all!