Credit card input form using jQuery

I am trying to create an easy to use credit card entry form on my website.

I need a form to display in the following format:



Any non-decimal number will be ignored, and the 5th character (represented by a hyphen) can be entered by the user as a number (becomes the fifth cc number), space, or hyphen.

eg. all inputs will be visible on the input as1234-1

1234 1
123whoops4 1



source to share

3 answers

Try the following:

    $(this).val(function(i, v)
        var v = v.replace(/[^\d]/g, '').match(/.{1,4}/g);
        return v ? v.join('-') : '';


Try it here:

Here's an explanation:


v.replace(/[^\d]/g, '')


we filter the input to only contain numbers. Then:



we will split the string of numbers into 4-digit chunks. Then:

return v ? v.join('-') : '';


if an array, we concatenate the array by inserting a dash between the pieces. Otherwise, we'll just set it to an empty string.



Your first problem is the assumption that all credit card numbers are four groups of four digits: ndash; this is not true .

Indeed, most Visa, MasterCard and Discover cards show their 16-digit account numbers in four groups. However, American Express card numbers are 15 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 to determine which card is entering. Amex cards start at 34 or 37, so you can use the Amex grouping and length requirements if the user starts entering an Amex card. Use the wiki chart as a starting point for formulating rules for other cards.

You can also check the checksum for cards that use Luhn's algorithm .



I would use a mask plugin. I've had great success with



All Articles