简体   繁体   中英

How can I validate Credit Card/Check Card Number?

I am making a custom view that checks valid card number. This is how I validate the card number.

boolean validateNumber(CharSequence number) {
            // This is for an exception.
            if(number.toString().startsWith("941082")) return true;

            int sum = 0;
            final int size = number.length();
            final int checkDigit = number.charAt(size - 1) - '0';

            boolean doubleDigit = true;

            for (int index = size - 1; --index >= 0; doubleDigit = !doubleDigit) {
                int digit = number.charAt(index) - '0';

                if (doubleDigit) {
                    digit *= 2;

                    if (digit > 9) {
                        //sum the two digits together,
                        //the first is always 1 as the highest
                        // double will be 18
                        digit = 1 + (digit % 10);
                    }
                }
                sum += digit;
            }

            return ((sum + checkDigit) % 10) == 0;
        }

But rarely, some cards aren't passed. How can I solve this issue?

source: https://www.ksnet.co.kr/Bbs?ci=NOTICE&c=NOTICE&fi=&fw=&f=ALL&q=BIN

The source provides BINs. However, even after them, card has more numbers and they are not valid somtimes with the function. How can I check those exception card numbers? (It's more than 3000 cases)

Those problems were caused mostly in Domestic(Korean) Card that starts with 9.

I`m using Kotlin Language

 private fun checksum(input: String) = addends(input).sum()
    
    private fun addends(input: String) = input.digits().mapIndexed { i, j ->
        when {
            (input.length - i + 1) % 2 == 0 -> j
            j >= 5 -> j * 2 - 9
            else -> j * 2
        }
    }

And Finally You using Function isValidCard

fun isValidCard(input: String): Boolean {
    val sanitizedInput = input.replace(" ", "")

    return when {
        valid(sanitizedInput) -> checksum(sanitizedInput) % 10 == 0
        else -> false
    }
}

This working for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM