2016-07-07 67 views
0

我想验证三个UITextFields和没有任何文本字段接受超过11个字符。如果我输入第12个字符,我的文本字段会变成红色,并且我无法前往下一个字段进行输入。UITextField验证错误

我从这个链接TextField Validation With Regular Expression有一些帮助与验证,但现在我似乎无法理解为什么我所有的文本字段不能接受超过11个字符?

- (BOOL)validateInputWithString:(NSString *)aString 
{ 
    NSString* regularExpression = @""; 

    if (aString == self.ipAddress.text) { 
     regularExpression = @"^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";   
    } else if (aString == self.username.text) { 
     regularExpression = @"^[A-Za-z][A-Za-z0-9]*$"; 
    } else if (aString == self.password.text) { 
     regularExpression = @"^[^\\s\\r\\n][0-9a-zA-Zk\\r\\[email protected]!#\\$\\^%&*()+=\\-\\[\\]\\\\\\';,\\.\\/\\{\\<>\\?\\s]*$"; 
    } 

    NSError *error = NULL; 
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: regularExpression 
                      options:NSRegularExpressionCaseInsensitive 
                      error:&error]; 
    if (error) { 
     NSLog(@"error %@", error); 
    } 

    NSUInteger numberOfMatches = [regex numberOfMatchesInString:aString 
                 options:0 
                  range:NSMakeRange(0, [aString length])]; 

    if([self.ipAddress.text length]>0 && [self.username.text length]>0 && [self.password.text length]>0) 
    { 
     enableLogin = YES; 

    } 
    return numberOfMatches > 0; 
} 

- (void)validateInputCallback:(NSNotification *) notification 
{ 
    UITextField* atextField = (UITextField *)[notification object]; 

    if ([self validateInputWithString:atextField.text]){ 

     //Turns the textfield green 
     atextField.layer.cornerRadius=8.0f; 
     atextField.layer.masksToBounds=YES; 
     atextField.layer.borderColor=[[UIColor greenColor]CGColor]; 
     atextField.layer.borderWidth= 1.0f; 

     } else { 
     //Turns the textfield red 
       atextField.layer.cornerRadius=8.0f; 
       atextField.layer.masksToBounds=YES; 
       atextField.layer.borderColor=[[UIColor redColor]CGColor]; 
       atextField.layer.borderWidth= 1.0f; 
    }  
} 

回答

0

无处不在,你使用==比较字符串是错误的,因为你比较指针不是字符串内容会有字符串的副本,以便指针会有所不同。将其全部更改为使用isEqualToString:

你不应该根据你想要比较的文本确定逻辑,你应该根据提供文本的文本字段选择正则表达式。