|
This snippet performs the Luhn Algorithm on a provided value in an attempt to determine if it's a valid credit card number
Author: PsychoCoder Category: C# Instructions: Provide the CC number you wish to validate Need a reference to the System.Text Namespace Code:
Copy to IDE: (Highlight) /// <summary>
///method utilizing the Luhn algorithm (or Luhn formula) to ///validate the provided credit card number /// </summary> /// <param name="value">number we're validating</param> /// <returns>True, if valid, otherwise false</returns> public bool DoesPassLuhnAlgorithmCheck(string value) { int sum = 0; int end = 0; try { if (string.IsNullOrEmpty(value)) throw new ArgumentException("The input value cannot be null or empty", value); StringBuilder sb = new StringBuilder(value.Length); //perform Luhn algorithm to determine if the value //provided is a valid cc number for (int i = 0; i < value.Length; i++) { //here we want only the numbers in the value being checked if (Char.IsDigit(value[i])) sb.Append(value[i]); } if (sb.Length > 18 || sb.Length < 15) return false; //determines whether the end digit will be multiplies by 2 bool multiplyByTwo = false; //now loop through what we have, looping backwards for (int i = sb.Length - 1; i >= 0; i--) { //get each digit one at a time int digit = Int32.Parse(sb.ToString(i, 1)); //if multiplyByTwo then we need to //multiple digit by 2 if (multiplyByTwo) { end = digit * 2; if (end > 9) end -= 9; } else //otherwise end is given the value of the end digit end = digit; //keep a running total sum += end; //change the value of multiplyByTwo multiplyByTwo = !multiplyByTwo; } //use mod 10 on the sum value int remainder = sum % 10; //if it's 0 (zero) then we got a valid value //otherwise we dont return (remainder == 0); } catch (ArgumentException ex) { return false; } } Highlighting: C# Date: August 27, 2010, 07:42:01 AM Views: 1229 |
|