Search code examples
iosxcodenspredicate

NSPredicate for mobile number validation


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


Solution

  • 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.