您的位置:首页 > 编程语言 > VB

Vb.net用Luhn's Algorthim辨别信用卡真假

2007-11-07 00:13 330 查看
Public Function ValidateLuhn(ByVal value As String) As Boolean

'I am using Luhn's Algorthim to validate the inserted number
'i then call this function later when i need to use it

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 = Integer.Parse(Digit)
If DoubleFlag Then
DigitValue *= 2
If DigitValue > 9 Then
DigitValue -= 9
End If
End If
CheckSum += DigitValue
DoubleFlag = Not DoubleFlag
Next

Return (CheckSum Mod 10 = 0)
这个是Luhn算法的函数代码,当然还需要输入让用户仅能输入数字

Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If TextBox1.Text.Length >= 4 Then e.Handled = True
If Not IsNumeric(e.KeyChar) Then e.Handled = True 'make users input 4 numbers only.
End Sub

再接下来就是按钮的代码

If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Then
MsgBox("please input you card number")
Else

If TextBox1.Text.Length = 4 Or TextBox2.Text.Length = 4 Or TextBox3.Text.Length = 4 Or TextBox3.Text.Length <= 8 Then 'most of the credit card number is more than 13 and less than 20
If ValidateLuhn(TextBox1.Text + TextBox2.Text + TextBox3.Text + TextBox4.Text) Then 'use Luhn's Algorthim check the credit card
MessageBox.Show("the Number is correct")
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""

Else

MessageBox.Show("the Number is not correct")
TextBox1.Text = ""
TextBox2.Text = " "
TextBox3.Text = ""
TextBox4.Text = ""
End If
Else

MessageBox.Show("your input is illegal")
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
End If

End If

不能上传图片...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐