Validate Credit Card Number

Asked

Viewed 16,306 times

10

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

  • 1

    http://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-algorithm

  • Validate in Client or Server?

  • @Randrade validate on the server

3 answers

9


You can use the attribute Creditcardattribute to validate. How you are using I believe you’re already familiar with the Data Annotations. It has an attribute called [Creditcard], which you can use for this purpose. To use the same simply mark on your property as follows:

[CreditCard(ErrorMessage = "Cartão de crédito inválido")]
public string CartaoCredito { get; set; }

In this answer you will be able to see more detailed.

You can implement your own attributes or methods to validate if you wish.

Some links to help:

Credit Card Validation Client Asp.Net.

Credit Card Attribute.

7

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

  1. Remove the last digit from the number. It is the checker;
  2. Write the numbers in reverse order;
  3. Multiply the odd digits by 2 and subtract 9 from all results greater than 9;
  4. Add up all the numbers;
  5. The checker digit (that of step 1) is the number you need to add to all other numbers summed 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)

Formats of Known Operators

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 took it from here.

In ASP.NET MVC

By attribute, as per @Randrade’s reply.

  • 1

    This algorithm is incorrect to validate credit card data. The correct algorithm is the algorithm of https://en.wikipedia.org/wiki/Luhn_algorithm

  • But that’s what my answer says. Luhm’s algorithm, explained.

  • 1

    The last step, after module 10 in the sum, is not enough to compare the result with the last digit. It would be necessary to do 10 - (sum MOD 10) to get this last digit. If you test with any CC number that does not finish in 5 you will see that the formula will not work.

  • I don’t understand anything. You better put another answer, because translated this example and tested the example number, 4556737586899855. The validator of the same link says that the number is validated.

  • 1

    It includes another answer mentioning yours. You have an observation about the last line of the explanation. If you change your answer I withdraw the remark. Are different answers.

3

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

  • Have only numbers
  • Have between 12 and 19 digits (actually no 17 digit CC)
  • The first 6 digits must indicate a valid IIN (Issuer Identification number). It is called BIN in banking.
  • Pass validation of Luhnn’s algorithm

The verification of the item BIN 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 inside these jumps the BIN belong to a different institution, including from different country. It is a classic mistake to believe that every card starting 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, because there is no way to validate a BIN via code without some kind of query, the validation can be done with the following algorithm

  • Check if the size of 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 also.
  • Check if the value has only numbers
  • Check if the number passes the validation of Luhnn’s algorithm

Below is a code in C#. It is just a way to understand because there is already in the current versions of ASP.net, validation by Attributes for this verification, as per @Randrade’s reply

Luhnn’s algorithm is represented in Response by @Gypsy Morrison Mendez with the caveat that on the last line, where 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)

Actually, there is no need to calculate the check Digit. Simply include the term in the sum and calculate module 10 of it. If zero 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.