校验工具类
1. 网址验证
/** 网址验证 */
+ (BOOL)validateUrlWithUrlStr:(NSString *)urlStr {
NSString *urlRegex = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
NSPredicate *urlPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegex];
return [urlPredicate evaluateWithObject:urlStr];
}
2. 邮箱验证
/** 邮箱验证 */
+ (BOOL)validateEmailWithEmailStr:(NSString *)emailStr {
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailPredicate evaluateWithObject:emailStr];
}
3. 身份证验证
+ (BOOL)validateIdentityCardNoWithCardNoStr:(NSString *)cardNoStr {
if (cardNoStr.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:[cardNoStr substringToIndex:17]];
int val;
BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
if (!isNum) {
return NO;
}
int sumValue = 0;
for (NSInteger i = 0; i < 17; i ++) {
sumValue += [[cardNoStr substringWithRange:NSMakeRange(i, 1)] intValue] * [[codeArray objectAtIndex:i] intValue];
}
NSString *strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d", sumValue % 11]];
if ([strlast isEqualToString:[[cardNoStr substringWithRange:NSMakeRange(17, 1)] uppercaseString]]) {
return YES;
}
return NO;
}
4. 手机号 || 固定电话号验证(包含400和800电话),这个校验方法写的比较开放,使用者可以根据自己需求自行修改正则表达式。
/** 手机号 || 固定电话号验证(包含400和800电话) */
+ (BOOL)validatePhoneNumberWithPhoneNumStr:(NSString *)phoneNumStr {
NSString *phoneRegex = @"\\d{3,4}-*\\d{7,8}|\\d{7,8}|(4|8)00-*(\\d{3})-*(\\d{4})|1\\d{10}";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
return [predicate evaluateWithObject:phoneNumStr];
}