How do you validate a credit card number?

Mindwatering Incorporated

Author: Tripp W Black

Created: 08/26/1999 at 07:51 PM

 

Category:
Notes Developer Tips
Formulas

How do you validate a credit card number?

This LotusScript function will validate the checksum of a credit card number:

Function ValidateCC( strCC As String ) As Integer
'Credit card validation algorithm
'By Mark Dixon, Ives Development
'Derived from http://prope.insa-lyon.fr/~fcoppola/credit.html
'Parameter: strCC
' A string containing the card number to be validated.
' May contain non-numeric characters, e.g. spaces or dashes
'Return value:
' True if the card number is good, False if the number is bad

Dim nCheckSum As Integer
Dim fDbl As Integer
Dim nCharPos As Integer
Dim nChar As Integer

fDbl = False
nCheckSum = 0

'Read the card number from right to left
For nCharPos = Len( strCC ) To 1 Step -1
nChar = Asc( Mid( strCC, nCharPos, 1 ) ) - Asc( "0" )
'Only process if the current character is a digit
If 0 <= nChar And nChar <= 9 Then
If ( fDbl ) Then
nChar = nChar * 2
If 10 <= nChar Then
nChar = nChar - 9
End If
End If
nCheckSum = nCheckSum + nChar
fdbl = Not fdbl
End If
Next

If nCheckSum Mod 10 = 0 Then ValidateCC = True Else ValidateCC = False
End Function


This JavaScript function does same thing before a web browser submit:

function ckCC(cardnum) {
// checksum only works on cards with less than 19 digits,
// cardnum - assumes card number entered w/ only numbers
if (cardnum.length > 19) return (false);
sum = 0;
mul = 1;
clen = cardnum.length;
for (i = 0; i < clen; i ++) {
digit = cardnum.substring(clen -i -1,clen -i);
tproduct = parseInt(digit ,10) * mul;
if (tproduct >= 10) {
sum += (tproduct % 10) + 1;
} else {
sum += tproduct;
}
if (mul == 1) {
mul ++;
} else {
mul --;
}
}
// check checksum
if ((sum % 10) == 0) {
return (true);
} else {
return (false);
}
}

previous page