Search code examples
objective-ccocoaif-statementnsalert

Add "informative text" to Alert if TextFields are empty


I am trying to code a NSAlert, that appears when when some NSTextFields are empty. I have 3 NSTextFields and I would like to have a NSAlert that shows which TextField ist empty in a list. It´s possible for me to do it for one text field, but how can I code it that the empty NSTextFields appear in the Alert ? If one Textfield is empty in the Altert should stand "TextField 1 is empty". If Field 1 and 2 are empty there should stand "TextField 1 is empty" and in the second row "TextField 2 is empty".

Here is my code:

if ([[TextField1 stringValue] length] == 0) {
    NSAlert* alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"OK"];
    [alert setMessageText:@"Error"];
    [alert setInformativeText:@"TextField 1 is empty"];
    [alert beginSheetModalForWindow:[self.view window] completionHandler:^(NSInteger result) {
        NSLog(@"Success");
    }];
} 

Solution

  • I would chain the if-statements to get the desired result. Set up a empty string and check every textField one after another. Add the error line to the string if it is empty. Don't forget to add a line break after appending a string.

    My words in code:

    NSString* errorMessage = @"";
    
    if ([[TextField1 stringValue] length] == 0) {
        errorMessage = @"TextField 1 is empty.\n";
    }
    
    if ([[TextField2 stringValue] length] == 0) {
        errorMessage = [errorMessage stringByAppendingString:@"TextField 2 is empty.\n"];
    }   
    
    if ([[TextField3 stringValue] length] == 0) {
        errorMessage = [errorMessage stringByAppendingString:@"TextField 3 is empty."];
    }
    
    if (![errorMessage isEqualToString:@""]) {
        NSAlert* alert = [[NSAlert alloc] init];
        [alert addButtonWithTitle:@"OK"];
        [alert setMessageText:@"Error"];
        [alert setInformativeText:errorMessage];
        [alert beginSheetModalForWindow:[self.view window] completionHandler:^(NSInteger result) {
            NSLog(@"Success");
        }];
    }
    

    This way you get dynamic output depending on which NSTextField was empty.