I'm trying to make an aesthetically pleasing credit card input form on my website.
I'd like a the form to display in the following format:
1234-1234-1234-1234
Any non decimal number would be ignored, and the 5th character (represented by the hyphen), could be entered by the user as a number (becomes the 5th number of the cc), a space, or a hyphen.
e.g. all of the following input would be seen in the input as 1234-1
12341
1234 1
1234-1
123whoops4 1
Try this:
$('#theInput').blur(function()
{
$(this).val(function(i, v)
{
var v = v.replace(/[^\d]/g, '').match(/.{1,4}/g);
return v ? v.join('-') : '';
});
});
Try it here: http://jsfiddle.net/hnbx4/
Here's the explanation:
First:
v.replace(/[^\d]/g, '')
we filter through the input to contain only numbers. Then:
.match(/.{1,4}/g);
we split the string of numbers into 4-digit chunks. Then:
return v ? v.join('-') : '';
if an array, we combine the array by inserting a dash between the chunks. Otherwise we just set it to an empty string.
Your first problem is the assumption that all credit card numbers are four groups of four numbers – this is not true.
It is true that most Visa, MasterCard, and Discover cards show their 16-digit account numbers in groups of four. However, American Express card numbers are 15 digits and are grouped 4-6-5. (I'm sure you don't want to alienate Amex cardholders.) Some older Visa cards have 13-digit account numbers.
You can apply some smarts in your script at detect what kind of card is being entered. Amex cards start with 34 or 37, so you can use the Amex grouping and length requirements if the user begins entering an Amex card. Use the Wiki chart as a starting place to formulate rules for other cards.
You can also validate the checksum for cards that use the Luhn algorithm.
I would use a mask plugin. I have had great success with http://digitalbush.com/projects/masked-input-plugin/