之前用正则表达式进行身份证号校验,但是有时候错误的身份证号也能通过前端校验,后来发现这个方法还是不错,把代码贴出了给大家:
// 身份证号验证 +(BOOL)validateIdentityCard:(NSString*)cardNo{ if (cardNo.length != 18) { return NO; } NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil]; NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil] forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]]; NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]]; int val; BOOL isNum = [scan scanInt:&val] && [scan isAtEnd]; if (!isNum) { return NO; } int sumValue = 0; for (int i =0; i<17; i++) { sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue]; } NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]]; if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) { return YES; } return NO; }
时间: 2024-10-31 04:36:07