3

I show UIAlertView with UIAlertViewStylePlainTextInput style. Then I try to validate for empty field like this:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 1) {
        if ([[alertView textFieldAtIndex:0].text length] > 0 ||
            [alertView textFieldAtIndex:0].text != nil ||
            [[alertView textFieldAtIndex:0].text isEqual:@""] == FALSE)
        {
            NSLog(@"error");
        }
        else
        {
            [self postToServer];
        }
    } else {
        //close alertview
    }
}

But it shows me an error message in log even if textfield not empty.

trumpetlicks
  • 7,033
  • 2
  • 19
  • 33
Pavel Kaljunen
  • 1,291
  • 2
  • 26
  • 53
  • 1
    modify this statement [alertView textFieldAtIndex:0].text length] > 0 as [alertView textFieldAtIndex:0].text length] == 0 – Sumanth Jun 22 '12 at 12:40

3 Answers3

2

This is because your if statement contains

[[alertView textFieldAtIndex:0].text length] > 0

which means if there is text then NSLog(@"error"); Your if should be:

if ((![alertView textFieldAtIndex:0].text) || [[alertView textFieldAtIndex:0].text isEqual:@""])
{
      NSLog("error");
}
graver
  • 15,183
  • 4
  • 46
  • 62
2

You can use the following

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 1) {
        NSString *text = [alertView textFieldAtIndex:0].text;

        if([text isEqualToString:@""])
        {
            NSLog(@"empty");
        }
        else {
            NSLog(@"Not empty");
        }
    }
}
Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56
1

First of all you have your NSLog(@"error"); in the area of the code which will be true if the textfield is longer than 0 length. This seems opposite of what you want!!!

Try this:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1){
        if ([[alertView textFieldAtIndex:0].text length] > 0 ||                   
            [[alertView textFieldAtIndex:0].text isEqual:@""] == FALSE){
            [self postToServer];
        }else{
            NSLog(@"error");
        }
    }else{
        //close alertview
    }
}

You may not need the length greater than zero in this if statement, but if you are somehow expecting invisible characters, than it may be OK to keep it!!!

trumpetlicks
  • 7,033
  • 2
  • 19
  • 33