demoshop

demo, trying to be the best_

驗證的公式就是必須要有的,這次demo參考了信用卡號碼的公式撰寫了這驗證的code,因為demo的新公司使用VB.net來寫asp.net所以這也是demo第一次寫VB算是一個經驗與紀錄吧。

先來說說信用卡的公式吧規則為【由右至左(共 1~ 16 ),奇數位乘上 1 ,偶數位乘上 2 ,共得出 16 個[新數字],再將每個[新數字]的十位數加上個位數,再產生[新新數字];共16個[新新數字]把所有16個[新新數字]合計加總,能整除10者,為正確卡號。 】,但是demo因為不想用減得所以程式內寫成由左至右,奇數×2偶數×1,這點有些不同還請注意

VB.NET

Dim creditCardNumber As String
creditCardNumber = "1234567891234563" '這裡請自行帶入你要驗證的號碼
If creditCardNumber.Length < 16 Then
    Page.ClientScript.RegisterStartupScript(Me.GetType(), "dd", "alert('錯誤數字只有" & creditCardNumber.Length & "碼');", True)
Else
    Dim Int(15) As Integer
    Dim x, num, sun As Integer
    For x = 0 To 15
        num = creditCardNumber.Substring(x, 1)
        If (x + 1) Mod 2 <> 0 Then '偶數乘1奇數乘2
            Int(x) = num * 2
        Else
            Int(x) = num
        End If
    Next
    For x = 0 To 15
        If (Int(x) > 9) Then
            Int(x) = (Int(x) Mod 10) + 1
        End If
        sun += Int(x)
    Next
    If (sun Mod 10 = 0) Then
        Page.ClientScript.RegisterStartupScript(Me.GetType(), "ddd", "alert('正確的信用卡');", True)
    Else
        Page.ClientScript.RegisterStartupScript(Me.GetType(), "dd", "alert('錯誤');", True)
    End If
End If

C#

string creditCardNumber = "1234567891234563"; //這裡請自行帶入你要驗證的號碼
 
if (creditCardNumber.Length < 16)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "dd", "alert('錯誤數字只有" + creditCardNumber.Length + "碼');", true);
}
else
{
    int[] Int = new int[16];
    int x = 0;
    int num = 0;
    int sun = 0;
    for (x = 0; x <= 15; x++)
    {
        num = Convert.ToInt16(creditCardNumber.Substring(x, 1));
        //偶數乘1奇數乘2
        if ((x + 1) % 2 != 0)
        {
            Int[x] = num * 2;
        }
        else
        {
            Int[x] = num;
        }
    }
    for (x = 0; x <= 15; x++)
    {
        if (Int[x] > 9)
        {
            Int[x] = (Int[x] % 10) + 1;
        }
        sun += Int[x];
    }
    if (sun % 10 == 0)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "ddd", "alert('正確的信用卡');", true);
    }
    else
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "dd", "alert('錯誤');", true);
    }
} 

 

http://www.csie.ntu.edu.tw/%7Er88009/%ABH%A5%CE%A5d%A5d%B8%B9%C0%CB%ACd%BE%B9.htm

回應討論