验证电话号码 ios

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13176083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:02:50  来源:igfitidea点击:

Validate phone number ios

iphoneiosregexipad

提问by Thomas Clayson

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

+或 00 然后是 6-14 个数字

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!

谢谢!

回答by whiteagle

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

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

这种方式好一些。如果您转义“\”,您的代码也能正常工作。

回答by Manuel Escrig

Copy & Pastemethod 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 sourceLibrary for validating Phone Numbers

或用于验证电话号码的开源

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

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

回答by jainvikram444

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

从行首开始匹配一个 +(或者可能是 1 或 0),这看起来不明确(但可能不取决于实现),因为捕获括号:() 打破了 + 和 ? 可能错位:匹配任何数字 0-9 1 或 0 次 6-14 次,然后匹配一位数字 0-9 然后行尾。您还注意到,任何反斜杠都必须加倍...... @"\b" 用于单词边界。你可能想尝试类似...

@"\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

回答by mandeep

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

txtlpmobile.text 是字符串(手机没有你要输入)

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

回答by NSurajit

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

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

这是经过测试的 RegularExpression 这将接受国家代码或不接受国家代码

回答by meaning-matters

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.

验证电话号码的唯一好方法是使用Google 惊人的 LibPhoneNumber。有一个 iOS 端口,或者您可以在隐藏的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.)

(我在几年前完成了后者,当时他们还没有 iOS 端口。工作就像一个魅力,即使在旧 iPhone 上也非常快。)

回答by User558

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

之后,您可以实现文本文件委托方法“shouldChangeCharactersInRange”,只需编写此代码

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

这里 ALLOWED_NUMBERS 和 kMobileNumberLimit 是

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

回答by Abhishek Mishra

In swift 4 -

在 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)
}

回答by HIMANSHU VARSHNEY

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

}

}