4.20. Validate Credit Card Numbers
Problem
You’re given the job of implementing an order form for a company that accepts payment by credit card. Since the credit card processor charges for each transaction attempt, including failed attempts, you want to use a regular expression to weed out obviously invalid credit card numbers.
Doing this will also improve the customer’s experience. A regular expression can instantly detect obvious typos as soon as the customer finishes filling in the field on the web form. A round trip to the credit card processor, by contrast, easily takes 10 to 30 seconds.
Solution
To keep the implementation simple, this solution is split into two parts. First we strip out spaces and hyphens. Then we validate what remains.
Strip spaces and hyphens
Retrieve the credit card number entered by the customer and store it into a variable. Before performing the check for a valid number, perform a search-and-replace to strip out spaces and hyphens. Replace all matches of this regular expression with blank replacement text:
[●-]| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Recipe 3.14 shows you how to perform this initial replacement.
Validate the number
With spaces and hyphens stripped from the input, the next regular expression checks if the credit card number uses the format of any of the six major credit card companies. It uses named capture to detect which brand of credit card the customer has:
^(?: (?<visa>4[0-9]{12}(?:[0-9]{3})?) | (?<mastercard>5[1-5][0-9]{14}) ...