话不多说,上代码
/*
* 常用信用卡卡号规则
* Issuer Identifier Card Number Length
* Diner's Club 300xxx-305xxx, 3095xx, 36xxxx, 38xxxx 14
* American Express 34xxxx, 37xxxx 15
* VISA 4xxxxx 13, 16
* MasterCard 51xxxx-55xxxx 16
* JCB 3528xx-358xxx 16
* Discover 6011xx 16
* 银联 622126-622925 16
*
* 信用卡号验证基本算法:
* 偶数位卡号奇数位上数字*2,奇数位卡号偶数位上数字*2。
* 大于10的位数减9。
* 全部数字加起来。
* 结果不是10的倍数的卡号非法。
* prefrences link:http://www.truevue.org/licai/credit-card-no
*
*/
+ (BOOL) isValidCreditNumber:(NSString*)value
{
NSString * lastNum = [[value substringFromIndex:(value.length-1)]copy];//取出最后一位
NSString * forwardNum = [[value substringToIndex:(value.length -1)]copy];//前15或18位
NSMutableArray * forwardArr = [[NSMutableArrayalloc] initWithCapacity:0];
for (int i=0; i<forwardNum.length; i++) {
NSString * subStr = [forwardNum substringWithRange:NSMakeRange(i, 1)];
[forwardArraddObject:subStr];
}
NSMutableArray * forwardDescArr = [[NSMutableArrayalloc] initWithCapacity:0];
for (int i =(forwardArr.count-1); i> -1; i--) {//前15位或者前18位倒序存进数组
[forwardDescArraddObject:forwardArr[i]];
}
NSMutableArray * arrOddNum = [[NSMutableArrayalloc] initWithCapacity:0];//奇数位*2的积 < 9
NSMutableArray * arrOddNum2 = [[NSMutableArrayalloc] initWithCapacity:0];//奇数位*2的积 >9
NSMutableArray * arrEvenNum = [[NSMutableArrayalloc] initWithCapacity:0];//偶数位数组
for (int i=0; i< forwardDescArr.count; i++) {
NSInteger num = [forwardDescArr[i] intValue];
if (i%2) {//偶数位
[arrEvenNumaddObject:[NSNumbernumberWithInt:num]];
}else{//奇数位
if (num * 2 <9) {
[arrOddNumaddObject:[NSNumbernumberWithInt:num * 2]];
}else{
NSInteger decadeNum = (num * 2) / 10;
NSInteger unitNum = (num * 2) % 10;
[arrOddNum2addObject:[NSNumbernumberWithInt:unitNum]];
[arrOddNum2addObject:[NSNumbernumberWithInt:decadeNum]];
}
}
}
__block NSInteger sumOddNumTotal =0;
[arrOddNumenumerateObjectsUsingBlock:^(NSNumber * obj,NSUInteger idx, BOOL *stop) {
sumOddNumTotal += [objintegerValue];
}];
__block NSInteger sumOddNum2Total =0;
[arrOddNum2enumerateObjectsUsingBlock:^(NSNumber * obj,NSUInteger idx, BOOL *stop) {
sumOddNum2Total += [objintegerValue];
}];
__block NSInteger sumEvenNumTotal =0 ;
[arrEvenNumenumerateObjectsUsingBlock:^(NSNumber * obj,NSUInteger idx, BOOL *stop) {
sumEvenNumTotal += [objintegerValue];
}];
NSInteger lastNumber = [lastNum integerValue];
NSInteger luhmTotal = lastNumber + sumEvenNumTotal + sumOddNum2Total + sumOddNumTotal;
return (luhmTotal%10 ==0)?YES:NO;
}
BOOL isNumber (char ch)
{
if (!(ch >= '0' && ch <='9')) {
return FALSE;
}
return TRUE;
}
+ (BOOL) isValidNumber:(NSString*)value{
const char *cvalue = [valueUTF8String];
int len = strlen(cvalue);
for (int i =0; i < len; i++) {
if(!isNumber(cvalue[i])){
return FALSE;
}
}
return TRUE;
}