Validate a Credit Card with Luhn’s Algorithm

Problem

You want to verify that a supplied credit card number is valid.

Solution

Manually compute and verify the checksum using Luhn’s algorithm, which all credit card numbers must satisfy.

Discussion

Luhn’s algorithm is a formula that combines the digits of a credit card (doubling alternate digits) and verifies that the final sum is divisible by 10. If it is, the credit card number is valid and could be used for an account.

Here’s a helper function that you can use to test Luhn’s algorithm:

Private Function ValidateLuhn(ByVal value As String) As Boolean Dim CheckSum As Integer = 0 Dim DoubleFlag As Boolean = (value.Length Mod 2 = 0) Dim Digit As Char Dim DigitValue As Integer For Each Digit In value DigitValue ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.