iOS开发判断身份证号是否合法

来源:互联网 发布:windows徽标键与t 编辑:程序博客网 时间:2024/05/29 09:14

// 身份证

/**

 * 功能:验证身份证是否合法

 * 参数:输入的身份证号

 */

+ (BOOL)isID:(NSString *)certID

{

   // NSLog(@"validateID.id=%@,length=%lu", certID, (unsigned long)certID.length);

    //add by liliumei 2014-12-04 使小x也能验证通过

    certID = [certID stringByReplacingOccurrencesOfString:@"x"withString:@"X"];

    

    //判断位数

    if (certID.length !=15 && certID.length !=18) {

        return NO;

    }

    

    NSString *carid = certID;

    long lSumQT =0;

    //加权因子

    int R[] = {7,9, 10, 5, 8, 4,2, 1, 6, 3, 7,9, 10, 5, 8, 4,2 };

    //校验码

    unsigned char sChecker[11] = {'1','0','X','9', '8', '7', '6', '5','4', '3', '2'};

    

    //15位身份证号转换成18

    NSMutableString *mString = [NSMutableStringstringWithString:certID];

    if ([certID length] ==15) {

        [mString insertString:@"19"atIndex:6];

        long p = 0;

        const char *pid = [mStringUTF8String];

        for (int i=0; i<=16; i++)

        {

            p += (pid[i]-48) * R[i];

        }

        

        int o = p%11;

        NSString *string_content = [NSStringstringWithFormat:@"%c",sChecker[o]];

        [mString insertString:string_content atIndex:[mString length]];

        carid = mString;

    }

    

    //判断地区码

    NSString * sProvince = [carid substringToIndex:2];

    if (![selfareaCode:sProvince]) {

        return NO;

    }

    

    //判断年月日是否有效

    //年份

    int strYear = [[selfgetStringWithLocation:6length:4withString:certID] intValue];

    //月份

    int strMonth = [[selfgetStringWithLocation:10length:2withString:certID] intValue];

    //

    int strDay = [[selfgetStringWithLocation:12length:2withString:certID] intValue];

    

    NSTimeZone *localZone = [NSTimeZonelocalTimeZone];

    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];

    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];

    [dateFormatter setTimeZone:localZone];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *date=[dateFormatter dateFromString:[NSString stringWithFormat:@"%d-%d-%d 12:01:01",strYear,strMonth,strDay]];

    if (date == nil) {

        return NO;

    }

    

    const char *PaperId  = [caridUTF8String];

    

    //检验长度

    if( 18 !=strlen(PaperId)) return -1;

    //校验数字

    for (int i=0; i<18; i++)

    {

        if ( !isdigit(PaperId[i]) && !(('X' == PaperId[i] ||'x' == PaperId[i]) && 17 == i) )

        {

            return NO;

        }

    }

    //验证最末的校验码

    for (int i=0; i<=16; i++)

    {

        lSumQT += (PaperId[i]-48) * R[i];

    }

    if (sChecker[lSumQT%11] != PaperId[17] )

    {

        return NO;

    }

    

    return YES;

}

0 0