Credit Card Validation In PHP With Regular Expressions

I had to do some credit card validation in both JavaScript and PHP recently. Looking around the net, I found some decent information but no scripts that fit the business rules I was given. There are a lot of different ways to approach validating a credit card. You can go with the loose rule of making sure it is only numbers and between 15 and 16 characters (or only numbers if you are accepting a wide array of cards). You can make the user select the card, and then make sure the number matches a regular expression for that type of card. That is basically what I did: $credit_card holds the type of card the user selected, and $cc_number has the credit card number the user entered. It then runs a switch statement to assign a regular expression based on the card, and has a default of 15 to 16 digits if there is no card match. [php] switch($credit_card) { case 'AMEX': $goodCC = '/^3[47]{1}[0-9]{13}$/'; break; case 'Visa': $goodCC = '/^4[0-9]{15}$/'; break; case 'Mastercard': $goodCC = '/^5[1-5]{1}[0-9]{14}$/'; break; case 'Discover': $goodCC = '/^6011[0-9]{12}$/'; break; default: $goodCC = '/^[0-9]{15,16}$/'; } if (!preg_match($goodCC,$cc_number)) { $errors = 'Your credit card number does not seem to match the card type you selected'; } [/php]

Posted In: PHP, regular expressions

Commentary