1

我的应用程序中有一个文本字段,我正在对电话号码(+00-0000000000)执行验证,用户必须先输入“+”,然后输入超过 2 位的国家代码,然后是国家代码“-”和“ -' 将输入任何无数字的手机号码。

我已经使用正则表达式完成了代码,但是当我最初在文本字段中输入任何字母代替“+”时,我的应用程序崩溃,当我输入 +00- 即 +countrycode- 然后任何字母说“abc”时,它接受的是错误的。我希望只有数字和 + 和 - 必须在文本字段中输入。如果输入了除数字和 + 和 - 以外的任何内容,例如,如果在文本字段中输入了字母,则应显示警报视图“请输入有效的手机号码”。

这是我的代码:

- (BOOL)validateInputWithString:(NSString *)aString
{
    NSString * const regularExpression = @"^([+]{1})([0-9]{2,6})([-]{1})([0-9]{10})$";
    NSError *error = NULL;
}



-(IBAction)Check:(id)sender{
    BOOL check = [self validateInputWithString:TextField.text];

    if(check == YES){
        NSLog(@"Hii");
        NSString *string= [NSString stringWithFormat:@"%@", TextField.text];
        NSArray *first = [string componentsSeparatedByString:@"-"];
        NSString *second = [first objectAtIndex:1];
        NSString *third = [first objectAtIndex:0];
        if([second length] < 11){
            NSLog(@"bang");
        }
        else{
            NSLog(@"Fault");
        }
        if([third length] > 3 || [third length] < 7){ 
            NSLog(@"Bang");
        }
        else{
            NSLog(@"fault");
        }
    }
    else{
        NSLog(@"FAULT");
    }
}

但是在我的代码中,当我在 +countrycode- 之后输入字母时,它会接受这是错误的,当我最初在我的文本文件中输入字母时,我的应用程序会在我的按钮单击时崩溃。

4

1 回答 1

1

您的应用程序因此崩溃:

NSString *string= [NSString stringWithFormat:@"%@", TextField.text];
NSArray *first = [string componentsSeparatedByString:@"-"];
NSString *second = [first objectAtIndex:1];
NSString *third = [first objectAtIndex:0];

首先你的变量名不好。为什么第一个是数组,第二个是第二个字符串,第三个是第一个字符串?没有意义,没有人会理解这段代码。

但是您的崩溃是因为您将字符串分开,然后在不检查它是否存在的情况下访问 objectAtIndex 1。如果字符串不包含,当然不存在-

这样的事情会解决你的问题:

NSString *string= [NSString stringWithFormat:@"%@", TextField.text];
NSArray *components = [string componentsSeparatedByString:@"-"];
NSString *strBeforeDash = [components objectAtIndex:0];
if ([components count] > 2) {
    NSLog(@"More than one \"-\" found");
    return;
}
if ([components count == 1) {
    NSLog(@"No \"-\" found");
    return;
}
NSString *strAfterDash = [components objectAtIndex:1];

并且- (BOOL)validateInputWithString:(NSString *)aString不验证任何内容,因为它既没有验证码也没有返回值。

于 2012-04-07T08:58:24.253 回答