3

How to validate a phone number (NSString *) by NSPredicate?

Rules:

minimum 10 digits

maximum 10 digits

the first digit must be 7,8 or 9 Thanks

Harshit K
  • 83
  • 1
  • 9

5 Answers5

6

An NSPredicate based on a regular expression will fit your requirements.

NSString *stringToBeTested = @"8123456789";

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

BOOL matched = [mobileNumberPred evaluateWithObject:stringToBeTested];

You don't need to keep the pattern in a string by itself, but regexes are complicated enough already so it makes the overall code clearer if you keep it out of the NSPredicate format string.

Monolo
  • 18,205
  • 17
  • 69
  • 103
1

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;
}
Kirtikumar A.
  • 4,140
  • 43
  • 43
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];
08442
  • 521
  • 2
  • 13
0

Below code will work for your requirement:

Function:

-(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];
}  

Call it:

if ([self validatePhone:@"9833112299"])
        {
            NSLog(@"Valid Phone Number");
        }
        else
        {
            NSLog(@"Invalid Phone Number");
        }
Raj Aryan
  • 363
  • 2
  • 15
0

Make it Global using 'extension' use it wherever required

In any one of your view controller class at the end after last } paste below code

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

when you want to validate yourTxtField in any ViewController class simply call as below:

if (yourTxtField.text?.validateMobile())!
{
 print("It is 10 digit, starting with 7/8/9")
}
else
{
 print("Invalid mobile number")
}
Community
  • 1
  • 1
vilas deshmukh
  • 389
  • 2
  • 5