验证身份证号Objective-c

@interface NSString (CheckIdTool)

- (BOOL)isValidIDNo;

@end
#import "NSString+CheckIdTool.h"

@implementation NSString (CheckIdTool)

- (BOOL)isValidIDNo {
    BOOL isVaid = [self isIdNoPattern] && [self isValidProvinceId] && [self isValidDate] && [self checkIDNoLastNum];
    return isVaid;
}

#pragma mark - private

//简单正则表达式
- (BOOL)isIdNoPattern {
    NSString *IdRegex = @"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([\\d|x|X]{1})$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", IdRegex];
    return [predicate evaluateWithObject:self];
}

//省(市)级行政区划码表
- (BOOL)isValidProvinceId {
    NSArray *proviceCode = @[@"11", @"12", @"13", @"14", @"15", @"21", @"22",
                             @"23", @"31", @"32", @"33", @"34", @"35", @"36", @"37", @"41", @"42", @"43",
                             @"44", @"45", @"46", @"50", @"51", @"52", @"53", @"54", @"61", @"62", @"63",
                             @"64", @"65", @"66", @"71", @"81", @"82", @"91"];
    NSString *proviceId = [self substringToIndex:2];
    for (NSString *ID in proviceCode) {
        if ([ID isEqualToString:proviceId]) {
            return YES;
        }
    }
    return NO;
}

// 判断日期是否有效
- (BOOL)isValidDate {
    NSString *dateString = [self substringWithRange:NSMakeRange(6, 8)];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyyMMdd";
    NSDate *date = [dateFormatter dateFromString:dateString];
    if (date) {
        return YES;
    }
    return NO;
}

- (NSArray *)cardIdArray {
    NSMutableArray *cardIdArray = [NSMutableArray array];
    for (int i = 0; i < self.length; i++) {
        [cardIdArray addObject:[self substringWithRange:NSMakeRange(i, 1)]];
    }
    return cardIdArray.copy;
}

//  计算身份证的第十八位校验码
- (NSString *)sumPower:(NSArray *)cardIdArray {
    NSArray *power = @[@7, @9, @10, @5, @8, @4, @2, @1, @6, @3, @7, @9, @10, @5, @8, @4, @2];
    NSArray *refNumber = @[@"1", @"0", @"X", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    int result = 0;
    for (int i = 0; i < power.count; i ++) {
        result += [power[i] integerValue] * [cardIdArray[i] integerValue];
    }
    return refNumber[(result % 11)];
    
}

//  验证第18位校验码是否正确
- (BOOL)checkIDNoLastNum {
    if (self.length != 18) return NO;
    NSArray *cardIdArray = [self cardIdArray];
    NSString *checkCode = [self sumPower:cardIdArray];
    NSString *lastNum = [self substringFromIndex:17];
    if ([lastNum isEqualToString:@"x"]) {
        lastNum = lastNum.uppercaseString;
    }
    if (![checkCode isEqualToString:lastNum]) {
        return NO;
    }
    return YES;
}

@end

你可能感兴趣的:(验证身份证号Objective-c)