-1

我有以下情况:我有 2 个文本字段,一个用于人名,另一个用于电子邮件输入。我现在要验证来自文本字段的输入,我使用“if 语句”来验证,如下所示:

NSString *name = [self.defaults objectForKey:@"Name"];
NSString *email = [self.defaults objectForKey:@"Email"];

 if ([name length] > 0 && NSStringIsValidName(name) && [email length] > 0 && NSStringIsValidEmail(email) ) {

        //All is okay, proceed to main menu. 



    } else {


        if (!NSStringIsValidName(name)) {
            alertMessage = @"Your name is not valid"

        }else if ([name length] == 0) {


            alertMessage = @"Name not written. Please write a name in settings";

            NSLog(@"3 name not written");

        }else if (!NSStringIsValidEmail(email)) {

            alertMessage = @"Your email is not valid";

            NSLog(@"4 email not valid");
        }else if ([email length] == 0) {

            alertMessage = @"Email not written. Please write a name in settings";

            NSLog(@"5 email not written ");

        }


            alertMessage = @"Name and email is not written or is not valid";

            NSLog(@"1 all not valid");

        //Show Alert message.... 
    }

如果只有姓名和电子邮件均未写入或无效,我现在想显示警报消息,然后仅在满足其条件时才显示其余的警报消息。使用我当前的代码,警报显示两次。例如,如果姓名和电子邮件都有效,我会为他们收到一条消息,并为他们各自的 if 语句收到两条消息。如果两个值都为真或假,如何only 执行一项操作,以便根据条件显示一个警报?

4

1 回答 1

1

让它成为你的第一个条件:

if (!NSStringIsValidName(name) && !NSStringIsValidEmail(email)) {
  alertMessage = @"Name and email is not written or is not valid";
  NSLog(@"1 all not valid");
} else if (!NSStringIsValidName(name)) {
  alertMessage = @"Your name is not valid"
} else if ([name length] == 0) {
  alertMessage = @"Name not written. Please write a name in settings";
  NSLog(@"3 name not written");
} else if (!NSStringIsValidEmail(email)) {
  alertMessage = @"Your email is not valid";
  NSLog(@"4 email not valid");
} else if ([email length] == 0) {
  alertMessage = @"Email not written. Please write a name in settings";
  NSLog(@"5 email not written ");
}
于 2013-11-05T18:34:30.330 回答