Luhn validation code – VB.Net (generic)

The Luhn algorithm is used for checking credit card numbers, mobile phone IMEI numbers and certain other numbers which may need validation when being input into a computer system. It is used more for ensuring that the number has been input by the operator correctly rather than checking that the number is “real” and there is still around about a 10% chance of an error slipping though. But it is better than nothing.

This is a little function that I had to write for my Computing coursework at A Level which does the above. It may be a bit long-winded, but it helps to explain how the algorithm works.

    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 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
    End Function

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>