Credit card numbers are not assigned at random. Each number, usually 16 digits long, must adhere to certain mathematical conditions to be valid. This is called the Luhn Check, and it is used by almost all major cards. If you support a Web site that accepts online payments, the first step in any process that accepts credit card numbers should be verifying the number. This tip shows how you can do this using VB6.
Using VB6, the credit card number is passed, as a string, to the function CCNumberValid. The string must contain only digits—no embedded spaces or dashes. The function returns True if the number is valid and False if not.
Public Function CCNumberValid(ByValCCNumber As String) As Boolean
Dim Result As Long
Dim Total As Long
Dim idx As Integer
Dim i As Integer
Dim j As Integer
j = 1
For i = Len(CCNumber) To 1 Step -1
Result = (CInt(Mid$(CCNumber, i, 1)) * j)
If Result >= 10 Then
Total = Total + (CInt(Mid$(CStr(Result), 1, 1)) _
+ CInt(Mid$(CStr(Result), 2, 1)))
Total = Total + Result
If j = 2 Then j = 1 Else j = 2
If Total Mod 10 = 0 Then
CCNumberValid = True
CCNumberValid = False
The fact that a credit card number is valid does not mean that it is actually assigned to an account or that the account is in good standing. But checking the validity of a number is the best and fastest way to weed out errors in number entry.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!