我有一个UITextField
,其中不允许使用特殊字符以及最多20个租船长度。
我正在使用以下代码来限制文本字段
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > limitPassportNumber) ? NO : YES;
为了停止特殊字符输入,我有以下代码。
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
现在,如果我需要同时返回两者,则只会执行一个。
有人可以建议。谢谢
答案 0 :(得分:1)
检查长度。如果太长,请返回NO
。否则,请检查字符是否有效。
您用于检查有效字符的代码效率很低。拆分并重新连接整个字符串不是检查它是否包含任何无效字符的好方法。
以下代码是处理您的案件的更好方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = textField.text.length + string.length - range.length;
if (newLength > limitPassportNumber) {
return NO; // too long
}
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
NSRange badRange = [string rangeOfCharacterFromSet:cs];
return badRange.location == NSNotFound;
}
答案 1 :(得分:0)
-(BOOL)isValidString:(NSString *)string{
NSString *regex = @"[A-Z0-9a-z]*";
NSPredicate *regTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([regTest evaluateWithObject:string]) {
return YES;
}
return NO;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string length] == 0)
return YES;
if ([string length] > 0 && [string length] <=20) {
NSString *newString = [textField text];
newString = [newString stringByReplacingCharactersInRange:range withString:string];
return [self isValidString:newString];
} else {
return NO;
}
}
答案 2 :(得分:-1)
NSString *str = @"[~!@#$%^&*()_+-]";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
if([[str evaluateWithObject:textfield.text]== YES] && [textfield.text length]<20){
// Do Something
}
else{
//Textfield has a special character or the text is greater than 20
}