Validating a credit card number (the check sum bit, I mean. The having sufficient credit part you need to figure out yourself.) is a really simple process. You can practically do it in your head.
For example:
- 4111 1111 1111 1111
- 1111 1111 1111 1114
- 1212 1212 1212 1218
- 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 8 = 30
- 30 mod 10 = 0
Here's a little perl subroutine to do it for ya. Returns
1 for valid and 0 for invalid.
sub is_valid_cc {
my $cc = shift() || return 0;
my @digits = reverse split( '', $cc ); # reverse the digits
for ($i=0; $i < scalar(@digits); $i++) {
$digits[$i] *= ($i%2) ? 2 : 1; # double the evens
}
my $string = join( '', @digits ); # recombine into a string
my $sum = 0;
foreach ( split( '', $string ) ) { # add the digits
$sum += $_;
}
return ($sum % 10) ? 0 : 1;
}
heropsychodreamer : the reason you can't just
double the
odd digits is that that
algorithm will break if the
credit card number has an
odd number of
digits (like
American Express and old
Visa credit cards).