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:
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.