Pavel Kaljunen
Pavel Kaljunen

Reputation: 1291

Validation for textfield in uialertview

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.

Upvotes: 3

Views: 3271

Answers (3)

trumpetlicks
trumpetlicks

Reputation: 7065

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

Upvotes: 1

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

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

Upvotes: 2

graver
graver

Reputation: 15213

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

Upvotes: 2

Related Questions