小编给大家分享一下基于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:@""]
看完了这篇文章,相信你对“基于Luhn算法格式校验用户输入的银行卡号是否正确”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。