简体   繁体   English

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

[英]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来源: https://www.ksnet.co.kr/Bbs?ci=NOTICE&c=NOTICE&fi=&fw=&f=ALL&q=BIN

The source provides BINs.源提供 BIN。 However, even after them, card has more numbers and they are not valid somtimes with the function.但是,即使在它们之后,卡也有更多的数字,并且它们有时对 function 无效。 How can I check those exception card numbers?我怎样才能检查那些例外卡号? (It's more than 3000 cases) (超过3000例)

Those problems were caused mostly in Domestic(Korean) Card that starts with 9.这些问题主要是在以 9 开头的国内(韩国)卡中引起的。

I`m using Kotlin Language我正在使用 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
        }
    }

And Finally You using Function isValidCard最后你使用 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.这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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