Guest User

Untitled

a guest
May 22nd, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. private static bool ValidateCardNumber( string cardNumber )
  2. {
  3. try
  4. {
  5. // Array to contain individual numbers
  6.  
  7. System.Collections.ArrayList CheckNumbers = new ArrayList();
  8. // So, get length of card
  9.  
  10. int CardLength = cardNumber.Length;
  11.  
  12. // Double the value of alternate digits, starting with the second digit
  13.  
  14. // from the right, i.e. back to front.
  15.  
  16. // Loop through starting at the end
  17.  
  18. for (int i = CardLength-2; i >= 0; i = i - 2)
  19. {
  20. // Now read the contents at each index, this
  21.  
  22. // can then be stored as an array of integers
  23.  
  24.  
  25. // Double the number returned
  26.  
  27. CheckNumbers.Add( Int32.Parse(cardNumber[i].ToString())*2 );
  28. }
  29.  
  30. int CheckSum = 0; // Will hold the total sum of all checksum digits
  31.  
  32.  
  33. // Second stage, add separate digits of all products
  34.  
  35. for (int iCount = 0; iCount <= CheckNumbers.Count-1; iCount++)
  36. {
  37. int _count = 0; // will hold the sum of the digits
  38.  
  39.  
  40. // determine if current number has more than one digit
  41.  
  42. if ((int)CheckNumbers[iCount] > 9)
  43. {
  44. int _numLength = ((int)CheckNumbers[iCount]).ToString().Length;
  45. // add count to each digit
  46.  
  47. for (int x = 0; x < _numLength; x++)
  48. {
  49. _count = _count + Int32.Parse(
  50. ((int)CheckNumbers[iCount]).ToString()[x].ToString() );
  51. }
  52. }
  53. else
  54. {
  55. // single digit, just add it by itself
  56.  
  57. _count = (int)CheckNumbers[iCount];
  58. }
  59. CheckSum = CheckSum + _count; // add sum to the total sum
  60.  
  61. }
  62. // Stage 3, add the unaffected digits
  63.  
  64. // Add all the digits that we didn't double still starting from the
  65.  
  66. // right but this time we'll start from the rightmost number with
  67.  
  68. // alternating digits
  69.  
  70. int OriginalSum = 0;
  71. for (int y = CardLength-1; y >= 0; y = y - 2)
  72. {
  73. OriginalSum = OriginalSum + Int32.Parse(cardNumber[y].ToString());
  74. }
  75.  
  76. // Perform the final calculation, if the sum Mod 10 results in 0 then
  77.  
  78. // it's valid, otherwise its false.
  79.  
  80. return (((OriginalSum+CheckSum)%10)==0);
  81. }
  82. catch
  83. {
  84. return false;
  85. }
  86. }
Add Comment
Please, Sign In to add comment