安卓實現銀行卡號驗證
* 判斷是否是銀行卡號
* @author WJ
* @param cardNo
* @return
*/
public static boolean checkBankCard(String cardNo) {
char bit = getBankCardCheckCode(cardNo
.substring(0, cardNo.length() - 1));
if (bit == 'N') {
return false;
}
return cardNo.charAt(cardNo.length() - 1) == bit;
}
private static char getBankCardCheckCode(String nonCheckCodeCardId) {
if (nonCheckCodeCardId == null
|| nonCheckCodeCardId.trim().length() == 0
|| !nonCheckCodeCardId.matches("\\d+")) {
// 如果傳的不是資料返回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');
}