Java 如何从电话管理器检查电话号码格式是否有效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25763935/
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-11 01:05:28  来源:igfitidea点击:

how to check phone number format is valid or not from telephony manager?

javaandroidvalidation

提问by Preeti

For checking the phone number(I have the pattern phone number like +918172014908) validation I use libphonenumber.jar file.. It checks the phone number according to the country is valid or not. I use this:--

为了检查电话号码(我有像 +918172014908 这样的模式电话号码)验证,我使用 libphonenumber.jar 文件。它根据国家/地区检查电话号码是否有效。我用这个:--

 PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); 
         PhoneNumber numberProto = phoneUtil.parse("phone_number", "");  
        phoneUtil.isValidNumber(numberProto) == true ? "valid" : "phone no not valid"

Its working fine..But this jar file takes a bit of memory.. Is there another way for checking the phone number format validation without libphonenumber.jar??? can you suggests something???

它工作正常..但是这个 jar 文件需要一些内存.. 有没有另一种方法可以在没有 libphonenumber.jar 的情况下检查电话号码格式验证???你能提出一些建议吗???

采纳答案by QArea

This answer might help you: https://stackoverflow.com/a/5959341

这个答案可能对你有帮助:https: //stackoverflow.com/a/5959341

To validate a string, use

要验证字符串,请使用

if (setNum.matches(regexStr))
where regexStr can be:

//matches numbers only
String regexStr = "^[0-9]*$"

//matches 10-digit numbers only
String regexStr = "^[0-9]{10}$"

//matches numbers and dashes, any order really.
String regexStr = "^[0-9\-]*$"

//matches 9999999999, 1-999-999-9999 and 999-999-9999
String regexStr = "^(1\-)?[0-9]{3}\-?[0-9]{3}\-?[0-9]{4}$" 

There's a very long regex to validate phones in the US (7 to 10 digits, extensions allowed, etc.). The source is from this answer: A comprehensive regex for phone number validation

在美国有一个很长的正则表达式来验证电话(7 到 10 位数字,允许扩展等)。来源来自这个答案:用于电话号码验证的综合正则表达式

String regexStr = "^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$"

回答by Ruchira Gayan Ranaweera

You can just use a simple regex. Say my telephone number format is 012-1234567

你可以只使用一个简单的regex. 说我的电话号码格式是 012-1234567

You can use \\d{3}-\\d{7}to validate them.

您可以使用\\d{3}-\\d{7}来验证它们。

Eg:

例如:

String number = "012-1234567";
Pattern pattern = Pattern.compile("\d{3}-\d{7}");
Matcher matcher = pattern.matcher(number); 
 if (matcher.matches()) {
      System.out.println("Phone Number Valid");
 }

回答by Haresh Chhelana

Try this:

尝试这个:

public static boolean isValidPhoneNo(CharSequence iPhoneNo) {
    return !TextUtils.isEmpty(iPhoneNo) &&
         Patterns.PHONE.matcher(iPhoneNo).matches();
}

回答by bhavesh kaila

Try this:

尝试这个:

/**
 * This method is used to set filter type of us phone number.
 * @param phone
 */
 public static void setFilterTypeOfUSPhoneNumber(final TextView phone){

        InputFilter filter = new InputFilter() { 
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
                    String pattern = "0123456789()- ";
                    for (int i = start; i < end; i++) { 
                            if (pattern.indexOf(source.charAt(i)) < 0 ||
                                    source.length() > 14) { 
                                    return ""; 
                            } 
                    } 
                    return null; 
            } 
        }; 

        phone.setFilters(new InputFilter[]{filter ,new InputFilter.LengthFilter(14)});
        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void afterTextChanged(Editable s) {

                if(s.length() > 1){

                    if(s.length() < 5){
                        if(s.toString().indexOf("(") != 0 ||
                                checkSpecialCharsPositions(s.toString())){
                            String str = s.toString();
                            str = replaceStrings(str);
                            str = "("+str;
                            s.clear();
                            s.append(str);
                            phone.setText(s);

                        }
                    }
                    else if(s.length() < 10){
                        if(s.toString().indexOf("(") != 0 ||
                                s.toString().indexOf(")") != 4 ||
                                checkSpecialCharsPositions(s.toString())){
                            String str = s.toString();
                            str = replaceStrings(str);
                            str = "("+str.substring(0, 3)+") "+str.substring(3);
                            s.clear();
                            s.append(str);
                            phone.setText(s);
                        }
                    }
                    else {
                        if(s.toString().indexOf("(") != 0 ||
                                s.toString().indexOf(")") != 4 ||
                                s.toString().indexOf("-") != 9 ||
                                checkSpecialCharsPositions(s.toString())){

                            String str = s.toString();
                            str = replaceStrings(str);
                            str = "("+str.substring(0, 3)+") "+str.substring(3,6) + "-" + str.substring(6);
                            s.clear();
                            s.append(str);
                            phone.setText(s);
                        }
                    }
                }
                Selection.setSelection(s,s.length());
            }

            private String replaceStrings(String str){
                str = str.replace("(", "");
                str = str.replace(")", "");
                str = str.replace(" ", "");
                str = str.replace("-", "");
                return str;
            }

            private boolean checkSpecialCharsPositions(String str){

                return (str.indexOf("(") != str.lastIndexOf("(") ||
                        str.indexOf(")") != str.lastIndexOf(")") ||
                        str.indexOf("-") != str.lastIndexOf("-"));
            }
        });

    }

回答by Ashish Lahoti

Considering these facts about phone number format:-

考虑到有关电话号码格式的这些事实:-

  1. Country Code prefix starts with ‘+' and has 1 to 3 digits
  2. Last part of the number, also known as subscriber number is 4 digits in all of the numbers
  3. Most of the countries have 10 digits phone number after excluding country code. A general observation is that all countries phone number falls somewhere between 8 to 11 digits after excluding country code.
  1. 国家/地区代码前缀以“+”开头,包含 1 到 3 位数字
  2. 号码的最后一部分,也称为订户号码,是所有号码中的 4 位数字
  3. 大多数国家/地区在排除国家/地区代码后都有 10 位电话号码。一般观察是,所有国家/地区的电话号码在排除国家/地区代码后都介于 8 到 11 位数字之间。
String allCountryRegex = "^(\+\d{1,3}( )?)?((\(\d{1,3}\))|\d{1,3})[- .]?\d{3,4}[- .]?\d{4}$";

Let's break the regex and understand,

让我们打破正则表达式并理解,

  • ^start of expression
  • (\\+\\d{1,3}( )?)?is optional match of country code between 1 to 3 digits prefixed with '+' symbol, followed by space or no space.
  • ((\\(\\d{1,3}\\))|\\d{1,3}is mandatory group of 1 to 3 digits with or without parenthesis followed by hyphen, space or no space.
  • \\d{3,4}[- .]?is mandatory group of 3 or 4 digits followed by hyphen, space or no space
  • \\d{4}is mandatory group of last 4 digits
  • $end of expression
  • ^表达的开始
  • (\\+\\d{1,3}( )?)?是 1 到 3 位数字之间的国家代码的可选匹配,前缀为“+”符号,后跟空格或无空格。
  • ((\\(\\d{1,3}\\))|\\d{1,3}是由 1 到 3 位数字组成的强制性组,带或不带括号,后跟连字符、空格或不带空格。
  • \\d{3,4}[- .]?是由 3 或 4 位数字组成的强制性组,后跟连字符、空格或无空格
  • \\d{4}是最后 4 位数字的强制性组
  • $表达结束

This regex pattern matches most of the countries phone number format including these:-

此正则表达式模式匹配大多数国家/地区的电话号码格式,包括:-

        String Afghanistan      = "+93 30 539-0605";
        String Australia        = "+61 2 1255-3456";
        String China            = "+86 (20) 1255-3456";
        String Germany          = "+49 351 125-3456";
        String India            = "+91 9876543210";
        String Indonesia        = "+62 21 6539-0605";
        String Iran             = "+98 (515) 539-0605";
        String Italy            = "+39 06 5398-0605";
        String NewZealand       = "+64 3 539-0605";
        String Philippines      = "+63 35 539-0605";
        String Singapore        = "+65 6396 0605";
        String Thailand         = "+66 2 123 4567";
        String UK               = "+44 141 222-3344";
        String USA              = "+1 (212) 555-3456";
        String Vietnam          = "+84 35 539-0605";

If you understood the above regex then you can also make country-specific regex patterns to validate phone number:-

如果您了解上述正则表达式,那么您还可以制作特定于国家/地区的正则表达式模式来验证电话号码:-

String indiaRegex = "^(\+\d{2}( )?)?((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$";
String singaporeRegex = "^(\+\d{2}( )?)?\d{4}[- .]?\d{4}$";

Source:https://codingnconcepts.com/java/java-regex-for-phone-number/

来源:https: //codingnconcepts.com/java/java-regex-for-phone-number/