PROWAREtech
ASP.NET: Validate Credit Card Number
Use Luhn Check to validate a credit card number with examples in C# and VB.NET (.NET Framework).
Here is an example of validating a credit card number using C#. If wanting to validate the credit card number on the client side using JavaScript then see this article.
bool ValidateCreditCardNumber(string cardNumber)
{
if (string.IsNullOrWhiteSpace(cardNumber))
return false;
System.Collections.Generic.IEnumerable<char> rev = cardNumber.Reverse();
int sum = 0, i = 0;
foreach (char c in rev)
{
if (c < '0' || c > '9')
return false;
int tmp = c - '0';
if ((i & 1) != 0)
{
tmp <<= 1;
if (tmp > 9)
tmp -= 9;
}
sum += tmp;
i++;
}
return ((sum % 10) == 0);
}
Here is an example of validating a credit card number using VB.NET.
Function ValidateCreditCardNumber(ByVal CardNumber As String) As Boolean
If String.IsNullOrWhiteSpace(CardNumber) Then
Return False
End If
Dim rev As System.Collections.Generic.IEnumerable(Of Char) = CardNumber.Reverse
Dim sum As Integer = 0, i As Integer = 0, c As Char
For Each c In rev
Dim a As Integer = Asc(c)
If a < 48 OrElse a > 57 Then
Return False
End If
Dim tmp As Integer = a - 48
If (i Mod 2) <> 0 Then
tmp *= 2
If tmp > 9 Then
tmp -= 9
End If
End If
sum += tmp
i += 1
Next
If (sum Mod 10) <> 0 Then
Return False
Else
Return True
End If
End Function
Comment