Validate credit card number

10

How do I validate credit card numbers? I will not be integrating with card operator, I just need to validate the number, as it does with validation with CPF.

    
asked by anonymous 09.11.2015 / 20:26

3 answers

9

You can use the CreditCardAttribute to validate. How are you using

09.11.2015 / 20:46
7

Validation of credit card numbers is usually done by Luhn's algorithm:

  • Remove the last digit from the number. He is the verifier;
  • Write the numbers in reverse order;
  • Multiply the odd house digits by 2 and subtract 9 from all results greater than 9;
  • Add all the numbers;
  • The check digit (the one from step 1) is the number you need to add to all other numbers added to get a module 10.
  • Example

    Passo                                                                                                       Total
    Número Original                          :  4   5   5   6   7   3   7   5   8   6   8   9   9   8   5   5   
    Tirando o último dígito                  :  4   5   5   6   7   3   7   5   8   6   8   9   9   8   5       
    Invertendo                               :  5   8   9   9   8   6   8   5   7   3   7   6   5   5   4       
    Multiplicando casas ímpares por 2        :  10  8   18  9   16  6   16  5   14  3   14  6   10  5   8       
    Subtraia 9 de todos os números acima de 9:  1   8   9   9   7   6   7   5   5   3   5   6   1   5   8       
    Somando todos os números                 :  1   8   9   9   7   6   7   5   5   3   5   6   1   5   8       85
    Mod 10: 85, módulo 10 = 5 (último dígito do cartão)
    

    Known Operator Formats

    Bandeira                    Intervalo de Início             Número de Dígitos
    -----------------------------------------------------------------------------
    American Express            34, 37                          15
    Diners Club - Carte Blanche 300, 301, 302, 303, 304, 305    14
    Diners Club - International 36                              14
    Diners Club - USA & Canada  54                              16
    Discover                    6011, 622126 até 622925, 644,   16
                                645, 646, 647, 648, 649, 65     
    InstaPayment                637, 638, 639                   16
    JCB                         3528 até 3589                   16
    Laser                       6304, 6706, 6771, 6709          16-19
    Maestro                     5018, 5020, 5038, 5893, 6304,   16-19
                                6759, 6761, 6762, 6763          
    MasterCard                  51, 52, 53, 54, 55              16-19
    Visa                        4                               13-16
    Visa Electron               4026, 417500, 4508, 4844, 4913, 16
                                4917    
    

    I pulled it out .

    In ASP.NET MVC

    By attribute, as answered by @Randrade .

        
    09.11.2015 / 20:48
    2

    The algorithm used to calculate the Check Digit of Credit Card Numbers is the Luhn's Algorithm , but it is not enough to just validate the information without taking into account the characteristics of a Credit Card number that are:

    • Only have numbers
    • Have 12 to 19 digits (there is actually no 17 digit CC)
    • The first 6 digits should indicate a valid Issuer identification number (IIN). It's called a BIN in banking.
    • Passing the Luhnn Algorithm Validation

    Verifying the BIN item requires an information base for comparison. There is no logic in the generation of BINs. You can have tracks for example that has jumps and within these jumps the BIN belong to a different institution, including a different country. It is a classic mistake to believe that every card that starts with 4 is VISA and with 5 is MasterCard, for example. Currently in Brazil this is even valid, because we have few Card companies which ends up reserving the 4 and 5 only for these two Flags.

    Leaving these aspects aside, as there is no way to validate a BIN via code without some type of query being done, validation can be done with the following algorithm

    • Check if the card number is between 12 and 19. Currently in Brazil it is rare to have a card other than 16. Some Hipercard had 19 but are already leaving with 16 as well.
    • Verify that the value has only numbers
    • Verify that the number passes through the validation of the Luhnn Algorithm

    Below a code in C #. It's just a way to understand because there are already in the current versions of ASP.net, Attributes validation for this check, according to @Randrade's answer

    The Luhnn Algorithm is represented in answer from @Cigano Morrison Mendez with the proviso that in the last line, where it is

    Mod 10: 85, módulo 10 = 5 (último dígito do cartão)
    

    Should be

    Mod 10: 85, módulo 10 = 5, Check Digit = 10 - 5 = 5 (último dígito da sequencia)
    

    In fact, there is no need to calculate the check digit . Simply include the term in the sum and compute the module 10 of it. If it is zero it is valid.

        // About the Algorithm
        /**
            @See https://en.wikipedia.org/wiki/Luhn_algorithm
            Steps:
            1 - From the rightmost Digit of a Numeric String, Double the value of every digit on odd positions
            2 - If the obtained value is greather than 9, subtract 9 from it
            3 - Sum all values
            4 - Calculate the Modulus of the value on 10 basis, if is zero so the String has a Luhnn Check Valid
        **/
    
        public static bool IsValidLuhnn(string val) {
    
            int currentDigit;
            int valSum = 0;
            int currentProcNum = 0; 
    
            for (int i = val.Length-1; i >= 0; i--) {           
                //parse to int the current rightmost digit, if fail return false (not-valid id)
                if(!int.TryParse(val.Substring(i,1), out currentDigit))
                    return false ;              
    
                currentProcNum = currentDigit << (1 +i & 1);                                                                    
                //summarize the processed digits
                valSum +=  (currentProcNum > 9 ? currentProcNum - 9 : currentProcNum);
    
            }  
    
            // if digits sum is exactly divisible by 10, return true (valid), else false (not-valid)
            // valSum must be greater than zero to avoid validate 0000000...00 value
            return (valSum > 0 && valSum % 10 == 0) ;
        } 
    
    
        public static bool isValidCreditCardNumber(string cc) {
            // rule #1, must be only numbers
            if (cc.All(Char.IsDigit) == false) {
                return false;
            }
            // rule #2, must have at least 12 and max of 19 digits
            if (12 > cc.Length || cc.Length > 19) {
                return false;
            }
            // rule #3, must pass Luhnn Algorithm
            return IsValidLuhnn(cc);
    
        }
    

    Can be tested here

        
    09.11.2016 / 21:11