【问题标题】:Validation for phone number in iOS [duplicate]在 iOS 中验证电话号码 [重复]
【发布时间】:2014-02-10 05:29:51
【问题描述】:

我是 iOS 新手。

我创建了一个 UITextField,我想对电话号码进行验证,以便只允许数字。 如果输入了任何字符或数字以外的任何字符,则不得接受它,例如它不能在 textField 中可见。

提前致谢。

【问题讨论】:

  • 您是否正在寻找一种方法来删除非数字数字、显示数字键盘和/或强制输入有效的电话号码(并因此对其进行格式化)?

标签: ios iphone objective-c


【解决方案1】:

您可以设置文本字段的键盘类型为Phone pad

制作宏

#define ACCEPTABLE_CHARECTERS @"0123456789."

并使用它

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

if (textField==textFieldAmount)
{
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    return [string isEqualToString:filtered];
}
return YES;
}

【讨论】:

  • 如果电话号码为+(country code) 10-digit no,则您的代码不起作用。所以,如果有regular expressions,那就太好了
  • @kalpesh 感谢重播
  • @MKR 它工作你必须在可接受的字符中添加 + 请检查。
  • @Kalpesh 你是对的,我只是说不用CharacterSet 你也可以使用regular expressions 来实现。
  • 我觉得这是我见过的最好的答案,即使是号码验证...
【解决方案2】:

@user3291536, 最好先尝试或搜索,然后发布您的查询。 无论如何,请按照这些链接,

Validating phone number in uitextfield

UITextField for Phone Number

how to perform validation on textfield for phone number entered by user in iphone

【讨论】:

    猜你喜欢
    • 2014-03-21
    • 1970-01-01
    • 2012-10-21
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多