Jump to content

Use the Luhn Algorithm to validate a credit card number

- - - - -

  • Please log in to reply
1 reply to this topic

#1
PsychoCoder

PsychoCoder

    Learning Programmer

  • Members
  • PipPipPip
  • 92 posts
//using System.Text


/// <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;

    }

}

SELECT * FROM Users WHERE Clue > 0;
ERROR: 0 results returned
Posted Image

#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
You know, there seems to be shorter variant available in Wikipedia.

public static bool IsLuhnValid(string value)
{
  return value.Where(c => Char.IsDigit(c)).Reverse()
    .SelectMany((c, i) => ((c - '0') << (i & 1)).ToString())
    .Sum(c => c - '0') % 10 == 0;
}





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users