如何验证信用卡/支票卡号?

问题描述

我正在制作一个检查有效卡号的自定义视图。 这就是我验证卡号的方式。

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

但很少有一些卡片没有通过。我该如何解决这个问题?

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

来源提供 BIN。但是,即使在它们之后,卡也有更多的数字,并且它们有时对功能无效。我如何检查这些例外卡号? (3000多例)

这些问题主要是由9开头的国内(韩国)卡引起的。

解决方法

我正在使用 Kotlin 语言

 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
        }
    }

最后你使用函数 isValidCard

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

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

这对我有用。