' Quote from
'Visual Basic 2005 Cookbook Solutions for VB 2005 Programmers
'by Tim Patrick (Author), John Craig (Author)
'# Publisher: O'Reilly Media, Inc. (September 21, 2006)
'# Language: English
'# ISBN-10: 0596101775
'# ISBN-13: 978-0596101770
Public Class Tester
Public Shared Sub Main
Console.WriteLine(VerifyCreditCard("123123123123123123"))
End Sub
Private Shared Function VerifyCreditCard(ByVal cardNumber As String) As Boolean
' ----- Given a card number, make sure it is valid. This method
' uses the Luhn algorithm to verify the number. This routine
' assumes that cardNumber contains only digits.
Dim counter As Integer
Dim digitTotal As Integer
Dim holdValue As Integer
Dim checkDigit As Integer
Dim calcDigit As Integer
Dim useCard As String
' ----- Perform some initial checks.
useCard = Trim(cardNumber)
If (IsNumeric(useCard) = False) Then Return False
' ----- Separate out the last digit, the check digit. For cards with
' an odd number of digits, prepend with a zero.
If ((Len(useCard) Mod 2) <> 0) Then useCard = "0" & useCard
checkDigit = useCard.Substring(Len(useCard) - 1, 1)
useCard = useCard.Substring(0, Len(useCard) - 1)
' ----- Process each digit.
digitTotal = 0
For counter = 1 To Len(useCard)
If ((counter Mod 2) = 1) Then
' ----- This is an odd digit position. Double the number.
holdValue = CInt(Mid(useCard, counter, 1)) * 2
If (holdValue > 9) Then
' ----- Break the digits (e.g., 19 becomes 1+9).
digitTotal += (holdValue \ 10) + (holdValue - 10)
Else
digitTotal += holdValue
End If
Else
' ----- This is an even digit position. Simply add it.
digitTotal += CInt(Mid(useCard, counter, 1))
End If
Next counter
' ----- Calculate the 10's complement of both values.
calcDigit = 10 - (digitTotal Mod 10)
If (calcDigit = 10) Then calcDigit = 0
If (checkDigit = calcDigit) Then Return True Else Return False
End Function
End Class
False