Verify that user input is correct bank card number

It is used to verify whether it is a bank card. The first 6 digits of the current 16-digit UnionPay card number are between 622126 and 622925, and the 7th to 15th digits are customized by the bank, which may be the card issuing branch, card issuing outlet, card issuing serial number, the 16th number. The bit is the check code.

 

package test;

 

public class BankCardTest {

public static void main(String[] args) {

        String card = "6227007200120897790";

        System.out.println("      card: " + card);

        System.out.println("check code: " + getBankCardCheckCode(card));

        System.out.println("Is it a bank card: "+checkBankCard(card));

    }

 

    /**

     * Verify bank card number

     * @param cardId

     * @return

     */

    public static boolean checkBankCard(String cardId) {

             char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));

             if(bit == 'N'){

                 return false;

             }

             return cardId.charAt (cardId.length () - 1) == bit;

    }

 

    /**

     * Use Luhm check algorithm to obtain check digit from bank card number without check digit

     * @param nonCheckCodeCardId

     * @return

     */

    public static char getBankCardCheckCode(String nonCheckCodeCardId){

        if(nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0

                || !nonCheckCodeCardId.matches("\\d+")) {

            //If the data is not passed, return N

            return 'N';

        }

        char[] chs = nonCheckCodeCardId.trim().toCharArray();

        int luhmSum = 0;

        for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {

            int k = chs[i] - '0';

            if(j % 2 == 0) {

                k *= 2;

                k = k / 10 + k % 10;

            }

            luhmSum += k;           

        }

        return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');

    }

 

}

 

From: http://outofmemory.cn/code-snippet/920/yanzheng-user-out-shifoushi-zhengque-yinxingqia-hao

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326861667&siteId=291194637