Swift Swift - 5 months ago 41
iOS Question

UITextField validation error

I am trying to validate three UITextFields and none of the textfields are accepting more than 11 characters. If I type the 12th character, my textfield turns red and I can't go to the next field to type.

I had a little help from this link TextField Validation With Regular Expression with validation but now I can't seem to understand why are all my textfields not accepting more than 11 characters?

- (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\\n@!#\\$\\^%&*()+=\\-\\[\\]\\\\\\';,\\.\\/\\{\\<>\\?\\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;
}
}

Answer

Everywhere you use == to compare strings is wrong, because you're comparing pointers not string contents and there will be copies of strings so pointers will be different. Change all of that to use isEqualToString:.

You shouldn't really determine logic based on the text you're trying to compare, you should choose the regex based on the text field that supplied the text.