前些日子写项目,测试提出要求要禁止表情的录入,在UITextField这个代理方法中shouldChangeCharactersInRange,只可以限制键盘上的表情不能录入,可是录入时联想上的表情仍是可以录入,因此最终用了下边的方法,可是可能还会有问题。数据库
究其缘由,测试说防止数据库的表被注入什么的,可是我感受这些活是后台要作的,后台直接拿传入的字符串直接做为数据库的查询条件,确定会有问题的,可是惹不起测试 ,只可以作了限制了!若是有更好的办法,欢迎指正。测试
- (void)viewDidLoad {代理
[super viewDidLoad];server
[[NSNotificationCenter defaultCenter]addObserver:selfci
selector:@selector(textDidChange:)rem
name:UITextFieldTextDidChangeNotification字符串
object:nil];string
}it
- (void)textDidChange:(NSNotification*)nf{io
UITextField *tf = (UITextField*)nf.object;
NSString *string = [self filterEmoji:tf.text];
if (string) {
tf.text = string;
}
}
- (NSString*)filterEmoji:(NSString*)text{
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionUseUnixLineSeparators error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:text
options:0
range:NSMakeRange(0, [text length])
withTemplate:@""];
if (![modifiedString isEqualToString:text]) {
return modifiedString;
}else{
return nil;
}
}
//在此要干掉通知
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}