5

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

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

user_apr
  • 719
  • 2
  • 10
  • 27
  • You can do [validation with regex](http://stackoverflow.com/questions/8634139/phone-validation-regex) – sanbhat Sep 10 '14 at 11:17

5 Answers5

10

This answer might help you: 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

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+))?$"
Community
  • 1
  • 1
QArea
  • 4,955
  • 1
  • 12
  • 22
3

Try this:

public static boolean isValidPhoneNo(CharSequence iPhoneNo) {
    return !TextUtils.isEmpty(iPhoneNo) &&
         Patterns.PHONE.matcher(iPhoneNo).matches();
}
kryger
  • 12,906
  • 8
  • 44
  • 65
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
  • 6
    Where does `Patterns` come from? – Lukasz Wiktor Jan 20 '17 at 15:24
  • 1
    It comes from core.java.android.util.Patterns but your answer doesn't specify that – Chris Maggiulli Jul 27 '17 at 09:14
  • 2
    As from `Patterns.Phone` [javadoc](https://developer.android.com/reference/android/util/Patterns.html#PHONE): it is not intended `for validating whether something is in fact a phone number. It will miss many things that are legitimate phone numbers.` – Paco Sep 01 '17 at 20:15
0

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

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

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");
 }
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • 1
    That's going to be a *long* list of regex expressions to cover all valid phone numbers in all countries. – Duncan Jones Sep 10 '14 at 11:17
  • @ArijitPatra yes. you can use List of phone numbers and iterate them and validate using this regex. it is just an example. – Ruchira Gayan Ranaweera Sep 10 '14 at 11:21
  • 1
    OR just /^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i – mach Sep 10 '14 at 11:23
0

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("-"));
            }
        });

    }
kryger
  • 12,906
  • 8
  • 44
  • 65
bhavesh kaila
  • 761
  • 1
  • 5
  • 25
0

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

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/

Ashish Lahoti
  • 648
  • 6
  • 8