IOS最严格身份证号验证
//身份证号
+ (BOOL)CheckIsIdentityCard: (NSString *)identityCard
{
//判断是否为空
if (identityCard==nil||identityCard.length <= 0) {
return NO;
}
//判断是否是18位,末尾是否是x
NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
if(![identityCardPredicate evaluateWithObject:identityCard]){
return NO;
}
//判断生日是否合法
NSRange range = NSMakeRange(6,8);
NSString *datestr = [identityCard substringWithRange:range];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat : @"yyyyMMdd"];
if([formatter dateFromString:datestr]==nil){
return NO;
}
//判断校验位
if(identityCard.length==18)
{
NSArray *idCardWi= @[ @"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2" ]; //将前17位加权因子保存在数组里
NSArray * idCardY=@[ @"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2" ]; //这是除以11后,可能产生的11位余数、验证码,也保存成数组
int idCardWiSum=0; //用来保存前17位各自乖以加权因子后的总和
for(int i=0;i<17;i++){
idCardWiSum+=[[identityCard substringWithRange:NSMakeRange(i,1)] intValue]*[idCardWi[i] intValue];
}
int idCardMod=idCardWiSum%11;//计算出校验码所在数组的位置
NSString *idCardLast=[identityCard substringWithRange:NSMakeRange(17,1)];//得到最后一位身份证号码
//如果等于2,则说明校验码是10,身份证号码最后一位应该是X
if(idCardMod==2){
if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]){
return YES;
}else{
return NO;
}
}else{
//用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码
if([idCardLast intValue]==[idCardY[idCardMod] intValue]){
return YES;
}else{
return NO;
}
}
}
return NO;
}
手机号
// 判断是否是号码
+ (BOOL)isPhoneNumber:(NSString *)phoneNumber {
NSString *regex = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
//@"^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d(8)$";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
BOOL isMatch = [pred evaluateWithObject:phoneNumber];
return isMatch;
}
邮箱号
#pragma mark - 检查是否是邮箱地址
+ (BOOL) checkEmailAddress:(NSString *)emailAddress {
NSString *strRegex = @"[A-Z0-9a-z._%+-]+@[A-Z0-9a-z._]+\\.[A-Za-z]{2,4}";
NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strRegex];
return [emailPredicate evaluateWithObject:emailAddress];
}