IT虾米网

iOS身份证验证

shasha 2018年06月23日 手机开发 1177 0

前言

在开发中,基本都需要到注册,而注册通常要输入一些身份信息,当然前端也是需要验证是否是合法的身份证才能提交。这篇文章只是放出个人的代码,不代表全正确!!!

扩展NSString代码

扩展NSString,添加以下方法:

  
- (BOOL)hyb_isValidPersonID { 
  return [NSStringhyb_isValidPersonID:self]; 
} 
  
+ (BOOL)hyb_isValidPersonID:(NSString *)personId { 
  // 判断位数 
  if (personId.length != 15 && personId.length != 18) { 
    return NO; 
  } 
  NSString *carid = personId; 
  long lSumQT = 0; 
  // 加权因子 
  int R[] ={7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; 
  // 校验码 
  unsigned char checkers[11]={'1','0','X', '9', '8', '7', '6', '5', '4', '3', '2'}; 
   
  // 将15位身份证号转换成18位 
  NSMutableString *str = [NSMutableStringstringWithString:personId]; 
  if (personId.length == 15) { 
    [strinsertString:@"19"atIndex:6]; 
    long p = 0; 
    const char *personId = [strUTF8String]; 
     
    for (int i = 0; i<= 16; i++) { 
      p += (personId[i] - 48) * R[i]; 
    } 
     
    int o = p % 11; 
    NSString *string_content = [NSStringstringWithFormat:@"%c", checkers[o]]; 
    [strinsertString:string_contentatIndex:[strlength]]; 
    carid = str; 
  } 
   
  // 判断地区码 
  NSString * sProvince = [caridsubstringToIndex:2]; 
  if (![self_areaCode:sProvince]) { 
    return NO; 
  } 
   
  // 判断年月日是否有效 
  // 年份 
  int strYear = [[self_substringWithString:caridbegin:6end:4]intValue]; 
  // 月份 
  int strMonth = [[self_substringWithString:caridbegin:10end:2]intValue]; 
  // 日 
  int strDay = [[self_substringWithString:caridbegin:12end:2]intValue]; 
   
  NSTimeZone *localZone = [NSTimeZone localTimeZone]; 
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
  [dateFormattersetDateStyle:NSDateFormatterMediumStyle]; 
  [dateFormattersetTimeStyle:NSDateFormatterNoStyle]; 
  [dateFormattersetTimeZone:localZone]; 
  [dateFormattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
  NSDate *date=[dateFormatterdateFrostr:[NSStringstringWithFormat:@"%d-%d-%d 12:01:01", 
                                              strYear, strMonth, strDay]]; 
  if (date == nil) { 
    return NO; 
  } 
   
  const char *pid  = [caridUTF8String]; 
  // 检验长度 
  if(18 != strlen(pid)) return NO; 
  // 校验数字 
  for (int i = 0; i < 18; i++) { 
    if ( !isdigit(pid[i]) && !(('X' == pid[i] || 'x' == pid[i]) && 17 == i) ) { 
      return NO; 
    } 
  } 
   
  // 验证最末的校验码 
  for (int i = 0; i <= 16; i++) { 
    lSumQT += (pid[i]-48) * R[i]; 
  } 
   
  if (checkers[lSumQT%11] != pid[17] ) { 
    return NO; 
  } 
  return YES; 
} 
  
  
#pragma mark - Private 
+ (NSString *)_substringWithString:(NSString *)strbegin:(NSInteger)beginend:(NSInteger )end { 
  return [strsubstringWithRange:NSMakeRange(begin, end)]; 
} 
  
评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!