Question

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.

Était-ce utile?

La solution

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");
}

Autres conseils

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");
        }
    }
}

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!!!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top