+ (BOOL)stringWithIDCardValidate:(NSString *)idCard{ BOOL flag = YES; if (idCard.length <= 0) { flag = NO; return flag; } NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$"; NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2]; flag = [identityCardPredicate evaluateWithObject:idCard]; //若是經過該驗證,說明身份證格式正確,但準確性還需計算 if(flag) { if(idCard.length==18) { //將前17位加權因子保存在數組裏 NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"]; //這是除以11後,可能產生的11位餘數、驗證碼,也保存成數組 NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"]; //用來保存前17位各自乖以加權因子後的總和 NSInteger idCardWiSum = 0; for(int i = 0;i < 17;i++) { NSInteger subStrIndex = [[idCard substringWithRange:NSMakeRange(i, 1)] integerValue]; NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue]; idCardWiSum+= subStrIndex * idCardWiIndex; } //計算出校驗碼所在數組的位置 NSInteger idCardMod=idCardWiSum%11; //獲得最後一位身份證號碼 NSString * idCardLast= [idCard substringWithRange:NSMakeRange(17, 1)]; //若是等於2,則說明校驗碼是10,身份證號碼最後一位應該是X if(idCardMod==2) { if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]) { return flag; }else { flag = NO; return flag; } }else { //用計算出的驗證碼與最後一位身份證號碼匹配,若是一致,說明經過,不然是無效的身份證號碼 if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) { return flag; } else { flag = NO; return flag; } } } else { flag = NO; return flag; } } else { return flag; } }