Thomas Clayson
Thomas Clayson

Reputation: 29925

Validate phone number ios

I need to validate an international phone number.

I know its difficult to validate an international phone number, so I'm going to keep it simple:

+ or 00 then 6-14 numbers

My current code using a regex isn't working for some reason which I can't work out. It just says that it cannot open the regex and crashes.

Here is my current code:

NSString *phoneRegex = @"^[\+(00)][0-9]{6,14}$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];

BOOL phoneValidates = [phoneTest evaluateWithObject:phoneNumber];

Where am I going wrong?

Thanks!

Upvotes: 28

Views: 56057

Answers (9)

NSurajit
NSurajit

Reputation: 421

NSString *phoneRegex = @"^((\\+)|(00))[0-9]{6,14}|[0-9]{6,14}$";

This is tested RegularExpression This will accept with country code OR without country code

Upvotes: 2

Abhishek Mishra
Abhishek Mishra

Reputation: 1655

In swift 4 -

func ValidateMobileNumber(txtFeid : UITextField, strChk : String, range: NSRange) -> Bool {

    if txtFeid.text!.count >= 10 {
        return false
    } 

    let formatePre = "^((\\+)|(00))[0-9]{6,14}$"
    let resultPredicate : NSPredicate = NSPredicate(format: "SELF MATCHES %@",formatePre)
    return resultPredicate.evaluate(with: strChk)
}

Upvotes: 0

User558
User558

Reputation: 1175

Easy way to validate phone number and password limit , just follow the below process.

if ((self.mobileTxtFld.text.length < 10 )) {
    [_mobileTxtFld becomeFirstResponder];
}
else if ((self.passwordTxtFld.text.length < kPasswordCharacterMinLimit) || (self.passwordTxtFld.text.length > kPasswordCharacterMaxLimit)) {
    // show alert
}

after that you can implement textfiled delegate method "shouldChangeCharactersInRange" in that just write this code

if (textField == _mobileTxtFld) {
    if([string rangeOfCharacterFromSet:ALLOWED_NUMBERS].location == NSNotFound){
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        if(newLength > kMobileNumberLimit - 1){
            if(textField.text.length != kMobileNumberLimit){
                textField.text  = [NSString stringWithFormat:@"%@%@",textField.text,string];
            }
            [textField resignFirstResponder];
            return NO;
        }
        else{
            return YES;
        }
    }
    else{
        return NO;
    }
}

return YES;

here ALLOWED_NUMBERS and kMobileNumberLimit are

#define kMobileNumberLimit 10
#define ALLOWED_NUMBERS [[NSCharacterSet decimalDigitCharacterSet] invertedSet]
#define minLimit 6
#define maxLimit 17

Upvotes: 0

whiteagle
whiteagle

Reputation: 1158

NSString *phoneRegex = @"^((\\+)|(00))[0-9]{6,14}$";

This way is bit better. Your code will work as well if you escape the "\".

Upvotes: 40

meaning-matters
meaning-matters

Reputation: 22946

The only good way to validate phone numbers is to use Google's amazing LibPhoneNumber. There's an iOS port, or you can run the JavaScript implementation in a hidden UIWebView.

(I've done the latter years ago when their was no iOS port yet. Works like a charm and is very fast even on old iPhones.)

Upvotes: 2

HIMANSHU VARSHNEY
HIMANSHU VARSHNEY

Reputation: 1

-(int)findLength:(NSString*)phoneNumber
{
    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];

int length = [phoneNumber length];

return length;

}

Upvotes: -4

Manuel Escrig
Manuel Escrig

Reputation: 2835

Copy & Paste method to validate phone numbers:

- (BOOL)validatePhone:(NSString *)phoneNumber
{
    NSString *phoneRegex = @"^((\\+)|(00))[0-9]{6,14}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];

    return [phoneTest evaluateWithObject:phoneNumber];
}

or Open source Library for validating Phone Numbers

https://github.com/iziz/libPhoneNumber-iOS

Upvotes: 16

mandeep
mandeep

Reputation: 384

txtlpmobile.text is the string(Mobile no ur gonna enter)

 int length = [self getLength:txtLpMobile.text];
            if(length == 10) {
                if(range.length == 0)
                    return NO;
            }
            if(length == 3){
                NSString *num = [self formatNumber:txtLpMobile.text];
                txtLpMobile.text = [NSString stringWithFormat:@"(%@) ",num];

                if(range.length > 0) {
                    txtLpMobile.text = [NSString stringWithFormat:@"%@",[num substringToIndex:3]];

                }
            } else if(length == 6) {
                NSString *num = [self formatNumber:txtLpMobile.text];
                txtLpMobile.text = [NSString stringWithFormat:@"(%@) %@-",[num  substringToIndex:3],[num substringFromIndex:3]];
                if(range.length > 0) {
                    txtLpMobile.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
                }
            }

            NSUInteger newLength;
            newLength = [txtLpMobile.text length] + [string length] - range.length;
            NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
            return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));

for formatting number

-(NSString*)formatNumber:(NSString*)mobileNumber
{
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];

    int length = [mobileNumber length];
    if(length > 10)
    {
        mobileNumber = [mobileNumber substringFromIndex: length-10];
    }
    return mobileNumber;
}

for getting length

-(int)getLength:(NSString*)mobileNumber
{
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];

    int length = [mobileNumber length];

    return length;
}

Upvotes: 1

Vikram Jain
Vikram Jain

Reputation: 5588

well it depends on how strict you want to be it doesn't seem like this regex is especially strict. this regex says:

start at beginning of line match one + (or maybe 1 or 0) which seems ambiguous (but may not be depending on implementation) because the capture parentheses:() breaks up the relationship of the + and the ? possibly misplaced : match any digit 0-9 1 or 0 times 6-14 times then one digit 0-9 then end of line. also you note that any backslash will have to be doubled... @"\b" for a word boundary. you may want to try something like...

@"\\b[\\d]{3}\\-[\\d]{3}\\-[\\d]{4}\\b"
would I think match your example, but it wouldn't match
(555) 555 - 5555 or
555.555.5555 or
+44 1865  55555

Upvotes: 2

Related Questions