信用卡號碼格式驗證-C#實現

 1  /// <summary>
 2         /// Is valid?
 3         /// </summary>
 4         /// <param name="context">Validation context</param>
 5         /// <returns>Result</returns>
 6         protected override bool IsValid(PropertyValidatorContext context)
 7         {
 8             var ccValue = context.PropertyValue as string;
 9             if (string.IsNullOrWhiteSpace(ccValue))
10                 return false;
11 
12             ccValue = ccValue.Replace(" ", "");
13             ccValue = ccValue.Replace("-", "");
14 
15             var checksum = 0;
16             var evenDigit = false;
17 
18             //http://www.beachnet.com/~hstiles/cardtype.html
19             foreach (var digit in ccValue.Reverse())
20             {
21                 if (!char.IsDigit(digit))
22                     return false;
23 
24                 var digitValue = (digit - '0') * (evenDigit ? 2 : 1);
25                 evenDigit = !evenDigit;
26 
27                 while (digitValue > 0)
28                 {
29                     checksum += digitValue % 10;
30                     digitValue /= 10;
31                 }
32             }
33 
34             return (checksum % 10) == 0;
35         }

 

判斷信用卡卡號是否正確

 
【信用卡號的驗證】


當你輸入信用卡號碼的時候,有沒有擔憂輸錯了而形成損失呢?其實能夠沒必要這麼擔憂,由於並非一個隨便的信用卡號碼都是合法的,它必須經過Luhn算法來驗證經過。
該校驗的過程:
一、從卡號最後一位數字開始,逆向將奇數位(一、三、5等等)相加。
二、從卡號最後一位數字開始,逆向將偶數位數字,先乘以2(若是乘積爲兩位數,則將其減去9),再求和。
三、將奇數位總和加上偶數位總和,結果應該能夠被10整除。
例如,卡號是:5432123456788881


則,奇數位和=35
偶數位乘以2(有些要減去9)的結果:1 6 2 6 1 5 7 7,求和=35。
最後35+35=70 能夠被10整除,認定校驗經過。


請編寫一個程序,從鍵盤輸入卡號,而後判斷是否校驗經過。經過顯示:「成功」,不然顯示「失敗」。
好比,用戶輸入:356827027232780
程序輸出:成功


【參考測試用例】
356406010024817     成功
358973017867744     成功
356827027232781     失敗
306406010024817     失敗

358973017867754     失敗html

相關文章
相關標籤/搜索