开发中,有时候,为了打造更好的用户体验,同时减轻服务器端的压力,需要对于一些如,手机号码,银行卡号,身份证号码进行格式校验
下面是判断银行卡号输入是否正确的代码(基于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:@""]