Skip to main content

Validate credit card number with Mod 10 algorithm in C#

Introduction

All you know what information contains in your NIC number. But do you know what information contains in the Credit Card Number? Following article provides brief details about what information contain in your credit card and demonstrates to how to validate credit card number using mod 10 (Luhn) algorithms with C#.

Background 

Card Length 
Typically, credit card numbers are all numeric and the length of the credit card number is between 12 digits to 19 digits. 
  • 14, 15, 16 digits – Diners Club
  • 15 digits – American Express
  • 13, 16 digits – Visa
  • 16 digits - MasterCard  
For more information please refer http://en.wikipedia.org/wiki/Bank_card_number.

Hidden information

  1.  Major Industry Identifier (MII) 
  2. The first digit of the credit card number is the Major Industry Identifier (MII). It designates the category of the entry which issued the card.    
    • 1 and 2 – Airlines 
    • 3 – Travel
    • 4 and 5 – Banking and Financial
    • 6 – Merchandising and Banking/Financial
    • 7 – Petroleum
    • 8 – Healthcare, Telecommunications
    • 9 – National Assignment 
  3. Issuer Identification Number 
  4. The first 6 digits are the Issuer Identification Number. It will identify the institution that issued the card. Following are some of the major IINs. 
  5. Amex – 34xxxx, 37xxxx 
  6. Visa – 4xxxxxx 
  7. MasterCard – 51xxxx – 55xxxx 
  8. Discover – 6011xx, 644xxx, 65xxxx 
  9. Account Number 
  10. Taking away the 6 identifier digits and the last digits, remaining digits are the person’s account number (7th and following excluding last digits) 
  11. Check digits   
Last digit is known as check digits or checksum. It is used to validate the credit card number using Luhn algorithm (Mod 10 algorithm). 
Luhn algorithm (Mod 10)  
The Luhn algorithm or Luhn formula, also known as the “modulus 10″ or “mod 10″ algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in US and Canadian Social Insurance Numbers. It was created by IBM scientist Hans Peter Luhn. (http://en.wikipedia.org/wiki/Luhn_algorithm)
When you implementing eCommerce application, It is a best practice validating credit card number before send it to the bank validation.
Here are the Luhn steps which can used to validate the credit card number. 
4 0 1 2 8 8 8 8 8 8 8 8 1 8 8 1  
Step 1 - Starting with the check digit double the value of every other digit (right to left every 2nd digit)  
Step 2 - If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers.
Step 2
Step 3 - Now add the un-doubled digits to the odd places
Step 4 - Add up all the digits in this number
If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid. 

Using the code   

Following code sample validates your credit card number against Mod 10. 
public static bool Mod10Check(string creditCardNumber)
{
    //// check whether input string is null or empty
    if (string.IsNullOrEmpty(creditCardNumber))
    {
        return false;
    }

    //// 1. Starting with the check digit double the value of every other digit 
    //// 2. If doubling of a number results in a two digits number, add up
    ///   the digits to get a single digit number. This will results in eight single digit numbers                    
    //// 3. Get the sum of the digits
    int sumOfDigits = creditCardNumber.Where((e) => e >= '0' && e <= '9')
                    .Reverse()
                    .Select((e, i) => ((int)e - 48) * (i % 2 == 0 ? 1 : 2))
                    .Sum((e) => e / 10 + e % 10);


    //// If the final sum is divisible by 10, then the credit card number
    //   is valid. If it is not divisible by 10, the number is invalid.            
    return sumOfDigits % 10 == 0;            
}


Helpful links : https://en.wikipedia.org/wiki/Luhn_algorithm

Ref : http://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-algorithm
http://stackoverflow.com/questions/29899715/should-i-use-the-creditcardattribute-to-validate-credit-card-numbers



------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ValidateCreditCard
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] cards = new string[] {
                ////http://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm
                //"378282246310005",  // American Express
                //"4012888888881881", // Visa
                //"6011111111111117", // Discover
                //"4222222222222", // Visa
                //"76009244561", // Dankort (PBS)
                //"5019717010103742", // Dakort (PBS)
                //"6331101999990016", // Switch/Solo (Paymentech)
                //"30569309025904", // Diners Club
                ////http://www.getcreditcardnumbers.com/
                //"5147004213414803", // Mastercard
                //"6011491706918120", // Discover
                //"379616680189541", // American Express
                //"4916111026621797", // Visa

                "340931724562876",//American Express
                "30387628228509",//Diners Club
                "6011076572567331",//Discover
                "214997288618159",//enRoute
                "3088498025303152",//JCB
                "210054331070006",//JCB 15 digit
                "5131157941313628",//MasterCard
                "4532133451218182",//Visa
                "4716102585525",//Visa 13 digit
                "869945432670749",//Voyager
            };

            foreach (string card in cards)
            {
                Console.WriteLine(IsValid(card));
            }

      
            Console.ReadLine();


            Console.WriteLine("******************************* Second Method ***********************************");
            Console.WriteLine("Please enter your credit card number here:");
            var ccnumber = Console.ReadLine();
            var results = Mod10Check(ccnumber);
            if (results)
            {
                Console.WriteLine("This Credit Card Number is valid!");
            }
            else
            {
                Console.WriteLine("Invalid Credit Card Number");
            }
            Console.ReadLine();
        }

        public static bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }

            string ccValue = value as string;
            if (ccValue == null)
            {
                return false;
            }
            ccValue = ccValue.Replace("-", "");
            ccValue = ccValue.Replace(" ", "");

            int checksum = 0;
            bool evenDigit = false;

            // http://www.beachnet.com/~hstiles/cardtype.html
            foreach (char digit in ccValue.Reverse())
            {
                if (digit < '0' || digit > '9')
                {
                    return false;
                }

                int digitValue = (digit - '0') * (evenDigit ? 2 : 1);
                evenDigit = !evenDigit;

                while (digitValue > 0)
                {
                    checksum += digitValue % 10;
                    digitValue /= 10;
                }
            }

            return (checksum % 10) == 0;
        }

        public static bool Mod10Check(string creditCardNumber)
        {
            //http://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-algorithm

            //// check whether input string is null or empty
            if (string.IsNullOrEmpty(creditCardNumber))
            {
                return false;
            }

            //// 1.    Starting with the check digit double the value of every other digit
            //// 2.    If doubling of a number results in a two digits number, add up
            ///   the digits to get a single digit number. This will results in eight single digit numbers                   
            //// 3. Get the sum of the digits
            int sumOfDigits = creditCardNumber.Where((e) => e >= '0' && e <= '9')
                            .Reverse()
                            .Select((e, i) => ((int)e - 48) * (i % 2 == 0 ? 1 : 2))
                            .Sum((e) => e / 10 + e % 10);


            //// If the final sum is divisible by 10, then the credit card number
            //   is valid. If it is not divisible by 10, the number is invalid.           
            return sumOfDigits % 10 == 0;
        }

    }
}

Comments

  1. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value. Im glad to have found this post as its such an interesting one! I am always on the lookout for quality posts and articles so i suppose im lucky to have found this! I hope you will be adding more in the future... dlrcollectionagency.com is a collection agency for small business

    ReplyDelete

Post a Comment

Popular posts from this blog

Tip/Trick: Fix Common SEO Problems Using the URL Rewrite Extension

Search engine optimization (SEO) is important for any publically facing web-site.  A large % of traffic to sites now comes directly from search engines, and improving your site’s search relevancy will lead to more users visiting your site from search engine queries.  This can directly or indirectly increase the money you make through your site. This blog post covers how you can use the free Microsoft  URL Rewrite Extension  to fix a bunch of common SEO problems that your site might have.  It takes less than 15 minutes (and no code changes) to apply 4 simple  URL Rewrite  rules to your site, and in doing so cause search engines to drive more visitors and traffic to your site.  The techniques below work equally well with both ASP.NET Web Forms and ASP.NET MVC based sites.  They also works with all versions of ASP.NET (and even work with non-ASP.NET content). [In addition to blogging, I am also now using Twitter for quick updates and to sh...

ASP.NET MVC - Set custom IIdentity or IPrincipal

Here's how I do it. I decided to use IPrincipal instead of IIdentity because it means I don't have to implement both IIdentity and IPrincipal. Create the interface interface ICustomPrincipal : IPrincipal { int UserId { get ; set ; } string FirstName { get ; set ; } string LastName { get ; set ; } } CustomPrincipal public class CustomPrincipal : ICustomPrincipal { public IIdentity Identity { get ; private set ; } public bool IsInRole ( string role ) { return false ; } public CustomPrincipal ( string email ) { this . Identity = new GenericIdentity ( email ); } public int UserId { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } } CustomPrincipalSerializeModel - for serializing custom information into userdata field in FormsAuthenticationTicket object. public class CustomPrincipalSerializeMode...

How to create a countdown timer in jquery

Create a countdown timer in jQuery First we need to include the jQuery library file to the HTML page to perform this task. To do that we need to understand that what exactly a jQuery library fie is ? JQuery library file is the library of JavaScript, which means this file contains the predefined functions of jQuery. We just need to call these functions to perform the task. jQuery functions reduces the lines of code and makes our task easy. As this jQuery library file contains the javascript functions so we need to call the function within <script> </script> tag. Now after including the file, we need to define a variable which will store that for how long you want the timer on the page(c=60) and now the time you set needs to be changed in hours , minutes and seconds using the code “ var hours = parseInt( time / 3600 ) % ;var minutes = parseInt( time / 60 ) % 60; var seconds = time % 60;” Now we need to put the condition if timer got finished (if (t...