判断银行卡


1.判断银行卡号

检验数字算法(Luhn Check Digit Algorithm),也叫做模数10公式,是一种简单的算法,用于验证银行卡、信用卡号码的有效性的算法。对所有大型信用卡公司发行的信用卡都起作用,

这些公司包括美国Express、护照、万事达卡、Discover和用餐者俱乐部等。这种算法最初是在20世纪60年代由一组数学家制定,现在Luhn检验数字算法属于大众,任何人都可以使用它。

算法:将每个奇数加倍和使它变为单个的数字,如果必要的话通过减去9和在每个偶数上加上这些值。如果此卡要有效,那么,结果必须是10的倍数。

// 判断银行卡

+ (BOOL) validateBankCardNumber: (NSString *)bankCardNumber

{

NSString *digitsOnly = bankCardNumber;

int sum = 0;

int digit = 0;

int addend = 0;

BOOL timesTwo = false;

for (NSInteger i = digitsOnly.length - 1; i >= 0; i--) {

digit = [digitsOnly characterAtIndex:i] - '0';

if (timesTwo) { addend = digit * 2; if (addend > 9) {

addend -= 9;

}

} else {

addend = digit;

}

sum += addend;

timesTwo = !timesTwo;

}

int modulus = sum % 10;

return modulus == 0;

return YES;

}

2.textfield银行卡四位输入

NSString *text = [self.cardText text];

NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];

string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];

if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {

[self popViewText:@"请输入数字" textField:_cardText];

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;

}

[self.cardText setText:newString];

return NO;

}

return YES;

3.返回去掉空格的字符串

-(NSString *)bankNumToNormalNum

{

return [self.cardText.text stringByReplacingOccurrencesOfString:@" " withString:@""];

}

4.调用

_cardNumber = [self bankNumToNormalNum];

BOOL isCard = [CheckMessage validateBankCardNumber:_cardNumber];

if (isCard) {

NSLog(@"1");

NSLog(@"%@, %@", _cardText.text, _cardNumber);

你可能感兴趣的:(判断银行卡)