I am using Objective-C TextFieldValidator(https://github.com/dhawaldawar/TextFieldValidator) custom class for validating textfields in my app, which have a function which validates regex on it:
-(BOOL)validate{
if(isMandatory){
if([self.text length]==0){
[self showErrorIconForMsg:strLengthValidationMsg];
return NO;
}
}
for (int i=0; i<[arrRegx count]; i++) {
NSDictionary *dic=[arrRegx objectAtIndex:i];
if([dic objectForKey:@"confirm"]){
TextFieldValidator *txtConfirm=[dic objectForKey:@"confirm"];
if(![txtConfirm.text isEqualToString:self.text]){
[self showErrorIconForMsg:[dic objectForKey:@"msg"]];
return NO;
}
}else if(![[dic objectForKey:@"regx"] isEqualToString:@""] && [self.text length]!=0 && ![self validateString:self.text withRegex:[dic objectForKey:@"regx"]]){
[self showErrorIconForMsg:[dic objectForKey:@"msg"]];
return NO;
}
}
self.rightView=nil;
return YES;
}
Now in my UIViewController I am using the following if
statement to validate all my textfields inherited from this custom TextFieldValidator in my register form:
tfFirstName.isMandatory = true
tfLastName.isMandatory = true
if (tfFirstName.validate() && tfLastName.validate()){
return true
}else{
return false
}
tfLastName
field is blank, but it seems like if
statement calls only tfFirstName.validate()
and always return true
, i.e. &&
operator is not working here. In Objective-C && works fine, but in Swift 3 it's not. Why is the &&
operator not working here and what's the solution?
When text is nil, your validate() function returns YES. In swift, UITextfield.text can produce a nil value. Change the first part of your validate function to something like...