只允许输入汉字、英文字母(姓名输入框)
NSArray *array = @[@"",@"1",@"e",@"zz11",@"呵呵",@"进口23",@"ee画",@" "];
for (NSString *str in array) {
BOOL b = [self isInputRule:str];
NSLog(@"%@:正则结果%@",str,b?@"YES":@"NO");
}
控制台输出结果:
2018-11-28 20:16:20.706204+0800 zhengze[1074:37374] :正则结果NO
2018-11-28 20:16:20.706383+0800 zhengze[1074:37374] 1:正则结果NO
2018-11-28 20:16:20.706501+0800 zhengze[1074:37374] e:正则结果YES
2018-11-28 20:16:20.706601+0800 zhengze[1074:37374] zz11:正则结果NO
2018-11-28 20:16:20.706685+0800 zhengze[1074:37374] 呵呵:正则结果YES
2018-11-28 20:16:20.706787+0800 zhengze[1074:37374] 进口23:正则结果NO
2018-11-28 20:16:20.706873+0800 zhengze[1074:37374] ee画:正则结果YES
2018-11-28 20:16:20.706974+0800 zhengze[1074:37374] :正则结果NO
//只要中文和字母a-zA-Z ➋➌➍➎➏➐➑➒是9宫格键盘输入时
- (BOOL)isInputRule:(NSString *)str {
NSString *pattern = @"^[a-zA-Z\u4e00-\u9fa5➋➌➍➎➏➐➑➒]+$";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
BOOL isMatch = [pred evaluateWithObject:str];
return isMatch;
}
参考:
UITextField只限中文、英文、数字输入和限制字符个数的实现方法
iOS 只能输入英文字母、数字、汉字
iOS-Main-UITextField只允许输入中,英文,数字
只允许输入数字、英文字母(身份证输入框)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == self.userCardNumTextField){//数字 字母
NSUInteger lengthOfString = string.length;
for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
unichar character = [string characterAtIndex:loopIndex];
//将输入的值转化为ASCII值(即内部索引值),可以参考ASCII表
// 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
if (character < 48) return NO; // 48 unichar for 0
if (character > 57 && character < 65) return NO;
if (character > 90 && character < 97) return NO;
if (character > 122) return NO;
}
NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
if (proposedNewLength > 18) {
return NO;//限制长度
}
}
return YES;
}
可见ASCII码
ASCII表
网友评论