Entry
How to check credit card digit validity
May 19th, 2000 21:17
Hiroto Sekine,
function ValidCard(CreditCard){
// Valid Input Syntax:
// Type1: **************** (16 columns)
// Type2: **** **** **** **** (19)
// Type3: ****-****-****-**** (19)
// Input is a credit card number in the form of a string.
// Validates numbers which use a "double-add-double MOD 10"
// check digit Output is False if not valid, True if valid.
var Validity = false; // Assume invalid card
var LN = CreditCard.length; // Get input value length
if ((16 <= LN) && (LN <= 19)){
LN --;
CheckSum = 0; // start with 0 checksum
Dbl = false; // Start with a non-doubling
//------------------------------------------------------------
// Beginning backward loop through string
//-------------------------------------------------------------
for (Idx = LN; Idx >= 0; Idx --){
Digit = CreditCard.substr(Idx, 1); // Isolate character
if (("0" <= Digit && Digit <= "9")
|| Digit == " " || Digit == "-"){
if (Digit != " " && Digit != "-"){ // Skip connector
Digit -= "0"; // Remove ASCII bias
if (Dbl){ // If in the "double-add" phase
Digit += Digit; // Then double first
if (Digit > 9){ // Cast nines
Digit -= 9;
}
}
Dbl = !Dbl; // Flip doubling flag
CheckSum += Digit; // Add to running sum
if (CheckSum > 9){ // Cast tens
CheckSum -= 10; // Same as MOD 10, but faster
}
}
} else {
return(Validity); // Invalid
}
}
Validity = (CheckSum == 0) ? true : false; // Must sum to 0
}
return(Validity);
}