下面小編就為大家帶來一篇判斷使用者輸入的銀行卡號是否正確的方法(基於Luhn演算法的格式校驗)。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧
開發中,有時候,為了打造更好的用戶體驗,同時減輕伺服器端的壓力,需要對於一些如,手機號碼,銀行卡號,身份證號碼進行格式校驗
以下是判斷銀行卡號輸入是否正確的程式碼(基於Luhn演算法的格式校驗):
##iOS程式碼: ##/**
* 银行卡格式校验
*
* @param cardNo 银行卡号
*
* @return
*/
+ (BOOL) checkCardNo:(NSString*) cardNo{
int oddsum = 0; //奇数求和
int evensum = 0; //偶数求和
int allsum = 0;
int cardNoLength = (int)[cardNo length];
int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
cardNo = [cardNo substringToIndex:cardNoLength - 1];
for (int i = cardNoLength -1 ; i>=1;i--) {
NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
int tmpVal = [tmpString intValue];
if (cardNoLength % 2 ==1 ) {
if((i % 2) == 0){
tmpVal *= 2;
if(tmpVal>=10)
tmpVal -= 9;
evensum += tmpVal;
}else{
oddsum += tmpVal;
}
}else{
if((i % 2) == 1){
tmpVal *= 2;
if(tmpVal>=10)
tmpVal -= 9;
evensum += tmpVal;
}else{
oddsum += tmpVal;
}
}
}
allsum = oddsum + evensum;
allsum += lastNum;
if((allsum % 10) == 0)
return YES;
else
return NO;
}
Androd程式碼:/**
* 匹配Luhn算法:可用于检测银行卡卡号
* @param cardNo
* @return
*/
public static boolean matchLuhn(String cardNo) {
int[] cardNoArr = new int[cardNo.length()];
for (int i=0; i<cardNo.length(); i++) {
cardNoArr[i] = Integer.valueOf(String.valueOf(cardNo.charAt(i)));
}
for(int i=cardNoArr.length-2;i>=0;i-=2) {
cardNoArr[i] <<= 1;
cardNoArr[i] = cardNoArr[i]/10 + cardNoArr[i]%10;
}
int sum = 0;
for(int i=0;i<cardNoArr.length;i++) {
sum += cardNoArr[i];
}
return sum % 10 == 0;
}
##在輸入銀行卡號過程中,通常,我們會每隔4位插入一個"-",類似"1332-2131-2313-1231-212"這種的格式可以透過以下方法實現:
設定textField的代理程式
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *text = [textField text];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
return NO;
}
text = [text stringByReplacingCharactersInRange:range withString:string];
text = [text stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSString *newString = @"";
while (text.length > 0) {
NSString *subString = [text substringToIndex:MIN(text.length, 4)];
newString = [newString stringByAppendingString:subString];
if (subString.length == 4) {
newString = [newString stringByAppendingString:@"-"];
}
text = [text substringFromIndex:MIN(text.length, 4)];
}
newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
if (newString.length >= 24) {
return NO;
}
[textField setText:newString];
return NO;
}
最後,怎麼得到不包含符號"-"的銀行卡號碼呢?
[self.textField.text stringByReplacingOccurrencesOfString:@"-" withString:@""]
以上是判斷使用者輸入的銀行卡號是否正確的方法_正規表示式的詳細內容。更多資訊請關注PHP中文網其他相關文章!