Cocoa中谓词(Predicate)提供了一个通用的查询方式处理数据,可以获取和指定数据的过滤形式,Cocoa实际开发中可以是使用NSPredicate及其父类NSComparisonPredicate和NSCompoundPredicate.其风格类似于SQL查询语言和正则表达式的混合体,提供了具有表现力的,自然语言界面来定义一个集合被搜寻的逻辑条件。一般来说稍微操作过数据库基本上很容易理解其中的方法,至于使用的方法也很简单。如下代码是实现方法:
BIDValidateMgr.h 代码:
// // BIDValidateMgr.h // TongHuiShop // // Created by eJiupi on 14-10-29. // Copyright (c) 2014年 xujinzhong. All rights reserved. // #import <Foundation/Foundation.h> @interface BIDValidateMgr : NSObject //手机号码验证 + (BOOL)validateMobile:(NSString *)mobile; //邮箱 + (BOOL)validateEmail:(NSString *)email; //身份证号 + (BOOL)validateIdentityCard: (NSString *)identityCard; @end
BIDValidateMgr.m 实现代码;
// // BIDValidateMgr.m // TongHuiShop // // Created by eJiupi on 14-10-29. // Copyright (c) 2014年 xujinzhong. All rights reserved. // #import "BIDValidateMgr.h" @implementation BIDValidateMgr //手机号码验证 + (BOOL)validateMobile:(NSString *)mobile { //手机号以13, 15,18开头,八个 \d 数字字符 NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"; NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex]; return [phoneTest evaluateWithObject:mobile]; } //邮箱 + (BOOL)validateEmail:(NSString *)email { NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; return [emailTest evaluateWithObject:email]; } //身份证号 + (BOOL)validateIdentityCard: (NSString *)identityCard { BOOL flag; if (identityCard.length <= 0) { flag = NO; return flag; } NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$"; NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2]; return [identityCardPredicate evaluateWithObject:identityCard]; } @end