Chetansinh N Zala
Chetansinh N Zala

Reputation: 478

How to check user entered phone number is valid or not in Objective c?

In my project i have validate a phone number with country code like if user enter number is 44557788991 and select country US.same like for other country how can i check the phone number is valid or not.

enter image description here

on button click i have to check number is valid or not.

Upvotes: 2

Views: 6115

Answers (2)

nice_pink
nice_pink

Reputation: 523

You can use NSDataDetector to check if the phone number is valid:

- (BOOL)isValidPhoneNumber:(NSString*)phoneNumber {
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:nil];
    NSTextCheckingResult *result = [detector firstMatchInString:phoneNumber options:NSMatchingReportCompletion range:NSMakeRange(0, [phoneNumber length])];
    if ([result resultType] == NSTextCheckingTypePhoneNumber) {
        return YES;
    }
    return NO;
}

Upvotes: 1

SAMIR RATHOD
SAMIR RATHOD

Reputation: 3510

I think you want to check the number country wise. for this you have to use following demo

https://github.com/rmaddy/RMPhoneFormat

for UK

    RMPhoneFormat *fmt = [[RMPhoneFormat alloc] initWithDefaultCountry:@"uk"];
    NSString *numberString = // the phone number to format
    NSString *formattedNumber = [fmt format:numberString];

for Australia

RMPhoneFormat *fmt = [RMPhoneFormat instance];
NSString *callingCode = [fmt callingCodeForCountryCode:@"AU"]; // Australia - returns 61
NSString *defaultCallingCode = [fmt defaultCallingCode]; // based on current Region Format (locale)

and so on...

Upvotes: 7

Related Questions