# TIP: Validating Credit Card Numbers

Thursday Sep 19th 2002 by James Johnston
Share:

This code demonstrates how to use VB to check the validity of a credit card number. Very useful in CGI!

If the number is in a valid format if returns 'True'. If the number is in an invalid format it returns 'False'. This algorithm should work with all credit cards. If a card validates with this code it doesn't mean that the card is actually good, it just means that the numbers are arranged in a valid format. If they don't validate then you've saved some time because you don't have to process the card to find out that it is definitely bad. I use this function in CGI forms that process credit card orders.

### Code

```Function CheckCard(CCNumber As String) _
As Boolean
Dim Counter As Integer, TmpInt As Integer

Counter = 1
TmpInt = 0

While Counter <= Len(CCNumber)
If IsEven(Len(CCNumber)) Then
TmpInt = Val(Mid\$(CCNumber, Counter, 1))
If Not IsEven(Counter) Then
TmpInt = TmpInt * 2
If TmpInt > 9 Then TmpInt = TmpInt - 9
End If
Counter = Counter + 1
Else
TmpInt = Val(Mid\$(CCNumber, Counter, 1))
If IsEven(Counter) Then
TmpInt = TmpInt * 2
If TmpInt > 9 Then TmpInt = TmpInt - 9
End If
Counter = Counter + 1
End If
Wend

If Answer = 0 Then CheckCard = True
End Function

Function IsEven(lngNumber As Long) As Boolean

If lngNumber Mod 2 = 0 Then
IsEven = True
Else
IsEven = False
End If

End Function
```
Share:
Home
Mobile Site | Full Site