This little function helps validating a given credit card number is legit:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?php function ValidateCreditCardNumber($cc_num) { $pattern = "/^3[47]\d{13}$/";//American Express if (preg_match($pattern,$cc_num)) { return true; } $pattern = "/^([30|36|38]{2})([0-9]{12})$/";//Diner's Club if (preg_match($pattern,$cc_num)) { return true; } $pattern = "/^6011\d{12}$/";//Discover Card if (preg_match($pattern,$cc_num)) { return true; } $pattern = "/^5[12345]\d{14}$/";//Mastercard if (preg_match($pattern,$cc_num)) { return true; } $pattern = "/^4\d{12}(\d\d\d){0,1}$/";//Visa if (preg_match($pattern,$cc_num)) { return true; } $pattern = "/^30[012345]\d{11}$/";//Diners if (preg_match($pattern,$cc_num)) { return true; } $pattern = "/^3[68]\d{12}$/";//Diners #2 if (preg_match($pattern,$cc_num)) { return true; } // Not valid return false; } ?> |
3 Responses to Validating a Credit Card
Zach | February 3, 2010 at 12:42 am
Excellent code man!
admin | February 3, 2010 at 9:15 am
Thanks. This one’s come in handy on more than one project. I hate pattern matching with a passion but it’s essential if you want to get down to the tricky stuff.
Zach | February 8, 2010 at 4:39 am
The code could probably be probably be more library-ized to say that:
if (is_cc($_POST[‘cc’], CC_VISA)) {
// sweet, we take that, and it’s valid
do_visa_stuff($_POST[‘cc’]);
}