二代身份证除了位数和各位表达的含义有限制外,还有一个校验和的问题,这篇文章就是来解决这个问题。网络上应该有对应的Java代码,我在这里这是把Java代码转换成了oc的代码,供大家使用。已经经过测试,验证正确。
- (BOOL)validateIdentityCard:(NSString *)identityCard
{
BOOL flag;
if (identityCard.length <= 0) {
flag = NO;
return flag;
}
flag = [identityCardPredicate evaluateWithObject:identityCard];
flag = flag && [self isRealIDCode:identityCard];
return flag;
}
- (BOOL)isRealIDCode:(NSString *)realCode {
if (realCode.length < 18) {
return false;
}
NSArray *ds = @[@7, @9, @10, @5, @8, @4, @2, @1, @6, @3, @7, @9, @10, @5, @8, @4, @2];
NSInteger total = 0;
for (NSInteger i = 0; i < 17; i++) {
NSRange currentRange = NSMakeRange(i, 1);
NSString *currentCode = [realCode substringWithRange:currentRange];
NSInteger currentCodeInteger = [currentCode integerValue];
NSInteger dsi = [ds[i] integerValue];
total += currentCodeInteger * dsi;
}
total = total % 11;
NSArray *ends = @[@"1", @"0", @"x", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
NSString *end = ends[total];
if ([end isEqualToString:[[realCode substringWithRange:NSMakeRange(17, 1)] lowercaseString]]) {
return YES;
}
return NO;
}