iphone - 如何对用户在 iPhone 中输入的电话号码的文本字段执行验证?

标签 iphone objective-c ios ipad uitextfield

我有一个应用程序,我有一个文本字段,用户可以在其中输入他的手机号码,包括他的国家代码。输入的手机号码格式为+91-9884715715。当用户输入他/她的手机号码时,最初应执行验证,用户输入的第一个值是'+',然后在+之后输入的号码不应小于0。

但在这之后,我对如何获取在 + 和 - 之间输入的数字数量感到困惑,因为用户输入国家代码和在 + 和 - 之间输入的数字长度必须是动态的而不是静态的。

最佳答案

试试这个,可能对你有帮助

- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:
    (NSString *)string {

    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == self.yourphoneNumberfield) {   
    NSArray *sep = [newString componentsSeparatedByString:@"-"];

    if([sep count] >= 2)
    {
        countryCode = [NSString stringWithFormat:@"%@",[sep objectAtIndex:0]];
        if ([[countryCode substringToIndex:1] isEqualToString:@"+"]) {
            phoneNumber = [NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
            return ([countryCode length]+[phoneNumber length]);
        }
    }
}
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{

    NSLog(@"Phone Number : %@",phoneNumber);
    if (textField == self.yourphoneNumberfield) {
        if ([phoneNumber length]<10) 
        { 
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Please Enter a Valid Mobile number" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
            [alert show]; 
        }
    }
    return YES;
}

关于iphone - 如何对用户在 iPhone 中输入的电话号码的文本字段执行验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9919288/

相关文章:

ios - 在 iOS 中绑定(bind)蜂窝网络和 Wi-Fi 连接

objective-c - mutableCopy 是否使包含的对象可变?

ios - UIBarButtonItem 未更新

IOS Audio Session 可行性

ios - XCode/Swift 无法更改文本标签位置

android - iOS 中的 Cordova geoLocation 插件无法正常工作

iphone - 将非事件 UIView 捕获为 UIImage

objective-c - 选择 HTML 文本区域时禁用 iPhone 键盘

iphone - 使用 MPMoviePlayerController 和锁定屏幕继续播放声音?

ios - 下载地点的网站和 priceLevel(Google places,Swift)