BOOL validateCreditCardNu mber NSString cardNumber NSNumberFormatter f

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
- (BOOL)validateCreditCardNumber:(NSString*)cardNumber {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
int sum = [[formatter numberFromString: [cardNumber substringFromIndex:[cardNumber length] - 1]] intValue];
NSInteger nDigits = [cardNumber length];
NSInteger parity = nDigits % 2;
for (int i = 0; i < nDigits - 2; i++) {
int digit = [[formatter numberFromString: [cardNumber substringWithRange:NSMakeRange(i, 1)]] intValue];
if (i % 2 == parity)
digit *= 2;
if (digit > 9)
digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}