3

如何通过 NSPredicate 验证电话号码(NSString *)?

规则:

最少 10 位数字

最多 10 位数字

第一个数字必须是 7,8 或 9 谢谢

4

5 回答 5

6

基于NSPredicate正则表达式的将满足您的要求。

NSString *stringToBeTested = @"8123456789";

NSString *mobileNumberPattern = @"[789][0-9]{9}";
NSPredicate *mobileNumberPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobileNumberPattern];

BOOL matched = [mobileNumberPred evaluateWithObject:stringToBeTested];

您不需要将模式单独保留在字符串中,但是正则表达式已经足够复杂,因此如果您将其保留在NSPredicate格式字符串之外,它会使整体代码更清晰。

于 2013-03-13T11:04:28.553 回答
2

You can just use below code

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   // return NO to not change text
 {
  if(textField.tag == 111)
    {
    if([self MobileNumberValidate:string] == TRUE)
    return YES;
    else
    return NO;
}
return YES;
}

#pragma mark - Mobile Number validation
- (BOOL)MobileNumberValidate:(NSString*)number
{
NSString *numberRegEx = @"[0-9]";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegEx];
if ([numberTest evaluateWithObject:number] == YES)
    return TRUE;
else
    return FALSE;
}
于 2014-06-26T11:27:38.390 回答
0
    NSString *phoneNumber = @"1234567890";
    NSString *phoneRegex = @"[789][0-9]{3}([0-9]{6})?"; 
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex]; 
    BOOL matches = [test evaluateWithObject:phoneNumber];
于 2013-03-13T11:02:38.677 回答
0

下面的代码将满足您的要求:

功能:

-(BOOL)validatePhone:(NSString *)enteredPhoneNumber
{
    NSString *phoneRegex = @"[789][0-9]{9}";
  // OR below for advanced type 
  //NSString *phoneRegex = @"^((\\+)|(00))[0-9]{6,14}$";

    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];

    return [phoneTest evaluateWithObject:enteredPhoneNumber];
}  

叫它:

if ([self validatePhone:@"9833112299"])
        {
            NSLog(@"Valid Phone Number");
        }
        else
        {
            NSLog(@"Invalid Phone Number");
        }
于 2017-12-29T06:43:51.300 回答
0

使用“扩展”使其成为全球性,在需要的地方使用它

在最后一个}之后的任何一个视图控制器类中粘贴下面的代码

extension String
{
func validateMobile() -> Bool
{
    return NSPredicate(format: "SELF MATCHES %@","[789][0-9].{9}").evaluate(with: self)
 }
 }

当您想在任何 ViewController 类中验证 yourTxtField 时,只需调用如下:

if (yourTxtField.text?.validateMobile())!
{
 print("It is 10 digit, starting with 7/8/9")
}
else
{
 print("Invalid mobile number")
}
于 2019-08-30T13:50:49.050 回答