如何验证Textfield输入

时间:2015-04-16 09:29:46

标签: ios objective-c iphone uitextfield

我有一个模块处理数据库调用功能,即我有一个文本字段,用户可以输入他们的手机号码。当用户输入手机号码的前4位数时,另一个称为操作员的域名将根据该文本字段中的4位数输入值自动更改。但是当用户输入有效的电话号码时,我的核心功能正常工作。当用户在文本字段中输入无效的数字时,我的应用程序崩溃当用户在文本字段中输入无效输入时,我不希望我的应用程序崩溃

我的示例代码:

 if(MobileNum.text.length ==4)
    {
        NSLog(@"MobileNum==>%@" ,MobileNum.text);

        Database *obj = [[Database alloc]init];
        NSMutableArray *dbArrray = [[NSMutableArray alloc]init];

        dbArrray =[obj getallRecords:MobileNum.text];

        NSString *value1 = [[dbArrray valueForKey:@"Operator"]objectAtIndex:0];

        if ([value1 isEqualToString:@""]) {
            NSString *data = @"Select Operator";
            NSString *data1 = @"Select Circle";

            operatorStr = [NSString stringWithFormat:@"%@", data];
            [operatorButton setTitle:operatorStr forState:UIControlStateNormal];
            circleStr = [NSString stringWithFormat:@"%@",data1];
            [circleButton setTitle:circleStr forState:UIControlStateNormal];
        }
        else
        {
            operatorStr = [[dbArrray valueForKey:@"Operator"]objectAtIndex:0];
            opString = operatorStr;
            NSLog(@"Operator Field==>%@",opString);
            [operatorButton setTitle:operatorStr forState:UIControlStateNormal];
            circleStr = [[dbArrray valueForKey:@"Circle"]objectAtIndex:0];
            cirString = circleStr;
            NSLog(@"Circle Field==>%@",cirString);
            [circleButton setTitle:circleStr forState:UIControlStateNormal];
        }
    }

并且我的textfield只接受起始数字,如7,8,9休息所有输入其拒绝和app崩溃

1 个答案:

答案 0 :(得分:0)

这样做

dbArrray =[obj getallRecords:MobileNum.text];

 if (dbArrray.count==0)
{
  // do nothing , like select the another user

  [operatorButton setTitle:@"Select Operator" forState:UIControlStateNormal];           
  [circleButton setTitle:@"Select Circle" forState:UIControlStateNormal];
 }
else
 {

   [operatorButton setTitle:[[dbArrray valueForKey:@"Operator"]objectAtIndex:0] forState:UIControlStateNormal];
   [circleButton setTitle:[[dbArrray valueForKey:@"Circle"]objectAtIndex:0] forState:UIControlStateNormal];
 }