08-24-2012, 03:34 PM
Well, you don't actually need to create a new module, you simply need to pop this into your code:
[code2=vbnet]Private Function ValidLuhn(ByVal Luhn As String) As Boolean
'this function accepts any 16 digit Luhn as long as it is numeric but checks 15 digit ones with the luhn algorithm
Dim ValidLuhn As Boolean = False
Dim ThisDigit As String
Dim Length As Integer
Dim N As Integer
Dim RunningTotal As Integer
If IsNumeric(Luhn) Then
'reverse the Luhn number and find out it's length
Luhn = StrReverse(Luhn)
Length = Len(Luhn)
'process each individual digit
For N = 1 To Length
ThisDigit = Luhn.Substring(N - 1, 1)
'if this number is the 2nd, 4th, 6th etc digit apply some extra processing
If N Mod 2 = 0 Then
'double the digit
ThisDigit *= 2
'if the digit is greater than 9 further processing is needed
If ThisDigit > 9 Then
'add both individual digits up and add them to the running total
ThisDigit = Val(ThisDigit.Substring(0, 1)) + Val(ThisDigit.Substring(1, 1))
RunningTotal += ThisDigit
Else
'otherwise just add the number to the running total
RunningTotal += ThisDigit
End If
Else
'otherwise just add this digit to the running total
RunningTotal += ThisDigit
End If
Next N
'if the resulting number is divisible by 10, the Luhn is correct
If RunningTotal Mod 10 = 0 Then
ValidLuhn = True
End If
End If
Return ValidLuhn
End Function[/code2]
Then, when the textbox loses focus, just call:
[code2=vbnet]If (ValidLuhn(TextBox1.Text)) Then
MsgBox("Valid!")
End If[/code2]
And there ya go!
[code2=vbnet]Private Function ValidLuhn(ByVal Luhn As String) As Boolean
'this function accepts any 16 digit Luhn as long as it is numeric but checks 15 digit ones with the luhn algorithm
Dim ValidLuhn As Boolean = False
Dim ThisDigit As String
Dim Length As Integer
Dim N As Integer
Dim RunningTotal As Integer
If IsNumeric(Luhn) Then
'reverse the Luhn number and find out it's length
Luhn = StrReverse(Luhn)
Length = Len(Luhn)
'process each individual digit
For N = 1 To Length
ThisDigit = Luhn.Substring(N - 1, 1)
'if this number is the 2nd, 4th, 6th etc digit apply some extra processing
If N Mod 2 = 0 Then
'double the digit
ThisDigit *= 2
'if the digit is greater than 9 further processing is needed
If ThisDigit > 9 Then
'add both individual digits up and add them to the running total
ThisDigit = Val(ThisDigit.Substring(0, 1)) + Val(ThisDigit.Substring(1, 1))
RunningTotal += ThisDigit
Else
'otherwise just add the number to the running total
RunningTotal += ThisDigit
End If
Else
'otherwise just add this digit to the running total
RunningTotal += ThisDigit
End If
Next N
'if the resulting number is divisible by 10, the Luhn is correct
If RunningTotal Mod 10 = 0 Then
ValidLuhn = True
End If
End If
Return ValidLuhn
End Function[/code2]
Then, when the textbox loses focus, just call:
[code2=vbnet]If (ValidLuhn(TextBox1.Text)) Then
MsgBox("Valid!")
End If[/code2]
And there ya go!