Credit Card Regular Expression

November 7th, 2008 by Mel Leave a reply »

So for the project I’m currently working on I need to verify credit card numbers input by the user. So I found a regular expression online that would do almost all of it, but it lacked a few necessary validations such as Discover cards and 13-digit Visas. So I modified it to work with almost all forms of Visa, MasterCard, American Express, and Discover cards.

It also supports white space and dashes in between blocks of numbers, as would be found on an actual credit card.

Here it is:
^(((4\d{3})|(5[1-5]\d{2})|(6011))[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4})|(3[4,7][\d\s-]{13})|(4[\d\s-]{12})$

It’s not 100% perfect for catching invalid Discover or 13-digit Visa cards but it will recognize valid ones. For best results, strip out any non-digits from the input string before running it through the regular expression.

Cheers!

Advertisement

Leave a Reply