Objective-C : 验证带有数字的文本字段

Objective-C : validating text field with number

我是 iOS 开发的新手。我想知道我们如何验证文本字段是否包含具有特定范围的数字,比如联系电话为 10?是否有可用的预定义函数?

谢谢。

+ (BOOL) validatePassword:(NSString *)passWord
{
   NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
   NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
   return [passWordPredicate evaluateWithObject:passWord];
}

要让 textfield 只接受数字,并且只能接受 10 位长度,您可以使用此功能。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
   NSString *acceptedCharsters = @"0123456789";

 NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 10) ? NO : YES;

NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptedCharsters] invertedSet];

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

    return [string isEqualToString:filtered];


return YES;
}