正好用到,作为纪录,代码丢完就走
//验证身份证号码
+(BOOL)checkIdentityCardNo:(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;
}
实际使用场景
- (void)textFieldDidEndEditing:(UITextField *)textField{
if (textField == _tfId) {
if (![MyTool checkIdentityCardNo:textField.text]) {
[self showMessage:@"请输入合法的身份证号"];
_tfId.text = @"";
}
}
}