74

How do I check if a phone number is valid or not? It is up to length 13 (including character + in front).

How do I do that?

I tried this:

String regexStr = "^[0-9]$";

String number=entered_number.getText().toString();  

if(entered_number.getText().toString().length()<10 || number.length()>13 || number.matches(regexStr)==false  ) {
    Toast.makeText(MyDialog.this,"Please enter "+"\n"+" valid phone number",Toast.LENGTH_SHORT).show();
    // am_checked=0;
}`

And I also tried this:

public boolean isValidPhoneNumber(String number)
{
     for (char c : number.toCharArray())
     {
         if (!VALID_CHARS.contains(c))
         {
            return false;
         }
     }
     // All characters were valid
     return true;
}

Both are not working.

Input type: + sign to be accepted and from 0-9 numbers and length b/w 10-13 and should not accept other characters

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Uday
  • 5,933
  • 9
  • 44
  • 76

16 Answers16

133

Use isGlobalPhoneNumber() method of PhoneNumberUtils to detect whether a number is valid phone number or not.

Example

System.out.println("....g1..."+PhoneNumberUtils.isGlobalPhoneNumber("+912012185234"));
System.out.println("....g2..."+PhoneNumberUtils.isGlobalPhoneNumber("120121852f4"));

The result of first print statement is true while the result of second is false because the second phone number contains f.

SMR
  • 6,628
  • 2
  • 35
  • 56
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
54

Given the rules you specified:

upto length 13 and including character + infront.

(and also incorporating the min length of 10 in your code)

You're going to want a regex that looks like this:

^\+[0-9]{10,13}$

With the min and max lengths encoded in the regex, you can drop those conditions from your if() block.

Off topic: I'd suggest that a range of 10 - 13 is too limiting for an international phone number field; you're almost certain to find valid numbers that are both longer and shorter than this. I'd suggest a range of 8 - 20 to be safe.

[EDIT] OP states the above regex doesn't work due to the escape sequence. Not sure why, but an alternative would be:

^[+][0-9]{10,13}$

[EDIT 2] OP now adds that the + sign should be optional. In this case, the regex needs a question mark after the +, so the example above would now look like this:

^[+]?[0-9]{10,13}$
Spudley
  • 166,037
  • 39
  • 233
  • 307
  • the slash is to escape the plus sign. It needs to be escaped since it is a regex reserved character. That's the only escape sequence in the regex, so I don't know why it would be complaining. But you could try replacing `\+` with `[+]`; that should also work. – Spudley Jun 15 '11 at 14:10
  • Its taking other special characters also...wen is used ^/+[0-9]{10,13}$ – Uday Jun 15 '11 at 14:11
  • forward slash is wrong; I specified back slash. But try the alternative string I suggested as well. – Spudley Jun 15 '11 at 14:13
  • Its not working sir...it taking other charcters also but i want 0-9 numbers, length 10-13 and including only + sign ..i used ^[+][0-9]{10,13}$ – Uday Jun 15 '11 at 14:14
  • The above regex is correct. What other characters is it letting through? Have you checked the value of `number.matches(regexStr)`? If it isn't false, what is it? Does it change if you put in a valid value? – Spudley Jun 15 '11 at 14:19
  • If i Enter 9347474324 - false(wrong) ()12#7456666 - false(correct) +919347474324 - true(correct) it means + is optional if its there also it shld accept. But its not letting through in wen we not entering +. – Uday Jun 15 '11 at 14:25
  • you didn't specify that you want to make the plus sign optional. If that's what you want, then you just need to put a question mark after it in the regex. I'll edit the answer again.... – Spudley Jun 15 '11 at 14:50
  • Thanx...but am not letting in when (number.matches(regexStr)==false && number.matches(regexStrsecond)==false) here regexStr = "^[+][0-9]{10,13}$"; and regexStrsecond = "^[0-9]{10,13}$"; this will work right? – Uday Jun 15 '11 at 14:57
  • no, you should only need one regex: the question mark makes the `+` optional. See my last edit to the answer. – Spudley Jun 15 '11 at 15:01
  • Its working nice for me. Thanks.. But I used the approach of Pattern.matcher and Pattern.compile(), which are easier to use. – YuDroid May 16 '12 at 09:27
  • what will be the regex for only 10 digit without +91 ? – hitesh141 Jun 29 '15 at 12:21
  • The backslash itself has to be escaped because it already has special meaning as an escape character for java strings. So the correct java regex would be `^\\+[0-9]{10,13}$`. – Ionoclast Brigham Aug 28 '15 at 21:05
38

To validate phone numbers for a specific region in Android, use libPhoneNumber from Google, and the following code as an example:

public boolean isPhoneNumberValid(String phoneNumber, String countryCode) {
    // NOTE: This should probably be a member variable.
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();

    try {
        PhoneNumber numberProto = phoneUtil.parse(phoneNumber, countryCode);
        return phoneUtil.isValidNumber(numberProto);
    } catch (NumberParseException e) {
        System.err.println("NumberParseException was thrown: " + e.toString());
    }
    
    return false;
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
DiscDev
  • 38,652
  • 20
  • 117
  • 133
  • 2
    You can also do `phoneUtil.parse(phonePrefix + phoneNumber, null)` if you don't have the region. – Andrew Dec 30 '16 at 20:42
  • 2
    This should be accepted answer. I tried to validate phone numbers for two countries and it detected them when wrong and when valid. While other answers used to show valid if I type country code + at least one extra digit – JustADev Apr 25 '17 at 10:57
  • Also make sure that number which you validate starts from '+' – Leo DroidCoder Dec 20 '17 at 12:51
  • 2
    Note that PhoneNumberUtils can become out of date. i.e. new numbers are added to carriers every now and then, so PhoneNumberUtils continues to report them as invalid while they are actually now valid. Ideally you would update the dependency once the new numbers were added but this requires an app update, so you may be blocking users until that occurs. – behelit Mar 16 '19 at 23:02
  • 1
    How do you even integrate this library? – TheRealChx101 Sep 29 '19 at 13:23
  • @TheRealChx101 this answer is 4+ years old and we stopped using this library many years ago. I don't remember the details. It was probably a gradle dependency of some kind. – DiscDev Sep 29 '19 at 19:30
  • Thanks. I was able to figure it out. – TheRealChx101 Sep 29 '19 at 22:19
  • 3
    To integrate this library, insert `implementation group: 'com.googlecode.libphonenumber', name: 'libphonenumber', version: '8.4.2'` to your Gradle. – Hawklike Jan 24 '20 at 23:40
  • The Android port for this lib https://github.com/MichaelRocks/libphonenumber-android – Codelicious Aug 05 '22 at 14:39
28

You can use android's inbuilt Patterns:

public boolean validCellPhone(String number) {
    return android.util.Patterns.PHONE.matcher(number).matches();
}

This pattern is intended for searching for things that look like they might be phone numbers in arbitrary text, not for validating whether something is in fact a phone number. It will miss many things that are legitimate phone numbers.

The pattern matches the following:

  • Optionally, a + sign followed immediately by one or more digits. Spaces, dots, or dashes may follow.
  • Optionally, sets of digits in parentheses, separated by spaces, dots, or dashes.
  • A string starting and ending with a digit, containing digits, spaces, dots, and/or dashes.
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
RazaHameed
  • 289
  • 3
  • 3
  • 3
    This returns true if it looks like a phone number not sure it validates if it is actually a phone number. Source: http://developer.android.com/reference/android/util/Patterns.html – Saher Ahwal Sep 15 '14 at 08:32
  • 1
    This answer is better than the `isGlobalPhoneNumber()` answer due to the fact both use simple regex to check the form of the number, and that Patterns.PHONE is superior regex (will match brackets etc). – Tom Oct 20 '15 at 21:55
  • I like this Pattern, it also has validation for email and a lot of other useful patterns. – G_V Mar 02 '17 at 15:04
  • 1
    "…not for validating whether something is in fact a phone number." – Stephan Feb 28 '18 at 10:32
11

you can also check validation of phone number as

     /**
     * Validation of Phone Number
     */
    public final static boolean isValidPhoneNumber(CharSequence target) {
        if (target == null || target.length() < 6 || target.length() > 13) {
            return false;
        } else {
            return android.util.Patterns.PHONE.matcher(target).matches();
        }

    }
Yurii Kot
  • 316
  • 3
  • 11
TejaDroid
  • 6,561
  • 4
  • 31
  • 38
  • 2
    `public final static boolean isValidPhoneNumber(CharSequence phone) { return phone != null && !(phone.length() < 6 || phone.length() > 13) && android.util.Patterns.PHONE.matcher(phone).matches(); }` – GameBug Sep 15 '16 at 06:33
  • 2
    Don't use the PHONE pattern on its own: "This pattern is intended for searching for things that look like they might be phone numbers in arbitrary text, not for validating whether something is in fact a phone number." – nasch Dec 06 '17 at 19:01
6
^\+?\(?[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})?

Check your cases here: https://regex101.com/r/DuYT9f/1

Maxim Firsoff
  • 2,038
  • 22
  • 28
  • 2
    While this may answer the question, it's better to include some context/explanation for the code because that makes it much more useful to future readers. Since this question already has an accepted answer and several upvoted answers, you may also want to explain how the answer differs from/improves upon the other ones. – EJoshuaS - Stand with Ukraine Jan 10 '18 at 20:24
5

You can use PhoneNumberUtils if your phone format is one of the described formats. If none of the utility function match your needs, use regular experssions.

inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • Additionally, there are several methods available from `PhoneNumberUtils` but what worked for me was `PhoneNumberUtils.formatNumberToE164(input, "PT")` where I am specifying Locale type of Portugal but could be generic as well. – Wahib Ul Haq Jun 03 '18 at 13:15
4

We can use pattern to validate it.

android.util.Patterns.PHONE

public class GeneralUtils {

    private static boolean isValidPhoneNumber(String phoneNumber) {
        return !TextUtils.isEmpty(phoneNumber) && android.util.Patterns.PHONE.matcher(phoneNumber).matches();
    }

}
LLIAJLbHOu
  • 1,313
  • 12
  • 17
  • 2
    `PHONE This pattern is intended for searching for things that look like they might be phone numbers in arbitrary text, not for validating whether something is in fact a phone number.` https://developer.android.com/reference/android/util/Patterns.html#PHONE – Eduards Denisjonoks Mar 29 '18 at 10:54
4
 String validNumber = "^[+]?[0-9]{8,15}$";

            if (number.matches(validNumber)) {
                Uri call = Uri.parse("tel:" + number);
                Intent intent = new Intent(Intent.ACTION_DIAL, call);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                }
                return;
            } else {
                Toast.makeText(EditorActivity.this, "no phone number available", Toast.LENGTH_SHORT).show();
            }
Csaba
  • 51
  • 4
4
val UserMobile = findViewById<edittext>(R.id.UserMobile)
val msgUserMobile: String = UserMobile.text.toString()
fun String.isMobileValid(): Boolean {
    // 11 digit number start with 011 or 010 or 015 or 012
    // then [0-9]{8} any numbers from 0 to 9 with length 8 numbers
    if(Pattern.matches("(011|012|010|015)[0-9]{8}", msgUserMobile)) {
        return true
    }
    return false
}

if(msgUserMobile.trim().length==11&& msgUserMobile.isMobileValid())
    {//pass}
else 
    {//not valid} 
David Buck
  • 3,752
  • 35
  • 31
  • 35
Mohamed ElNady
  • 304
  • 1
  • 2
  • 8
1
^\+201[0|1|2|5][0-9]{8}

this regex matches Egyptian mobile numbers

m.yuki
  • 815
  • 1
  • 10
  • 19
0

Here is how you can do it succinctly in Kotlin:

fun String.isPhoneNumber() =
            length in 4..10 && all { it.isDigit() }
Gulzar Bhat
  • 1,255
  • 11
  • 13
  • This is nice and concise code, however, it's not a comprehensive check for phone number validity in general. See here: https://github.com/googlei18n/libphonenumber/blob/master/FALSEHOODS.md – Peter F Apr 02 '19 at 09:03
0

I got best solution for international phone number validation and selecting country code below library is justified me Best library for all custom UI and functionality CountryCodePickerProject

Venkatesh
  • 1,034
  • 13
  • 25
0

What about this method:

private static boolean validatePhoneNumber(String phoneNumber) {
    // validate phone numbers of format "1234567890"
    if (phoneNumber.matches("\\d{10}"))
        return true;
        // validating phone number with -, . or spaces
    else if (phoneNumber.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}"))
        return true;
        // validating phone number with extension length from 3 to 5
    else if (phoneNumber.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}"))
        return true;
        // validating phone number where area code is in braces ()
    else if (phoneNumber.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}"))
        return true;
        // Validation for India numbers
    else if (phoneNumber.matches("\\d{4}[-\\.\\s]\\d{3}[-\\.\\s]\\d{3}"))
        return true;
    else if (phoneNumber.matches("\\(\\d{5}\\)-\\d{3}-\\d{3}"))
        return true;

    else if (phoneNumber.matches("\\(\\d{4}\\)-\\d{3}-\\d{3}"))
        return true;
        // return false if nothing matches the input
    else
        return false;
}

  System.out.println("Validation for 1234567890 : " + validatePhoneNumber("1234567890"));
  System.out.println("Validation for 1234 567 890 : " + validatePhoneNumber("1234 567 890")); 
  System.out.println("Validation for 123 456 7890 : " + validatePhoneNumber("123 456 7890"));
  System.out.println("Validation for 123-567-8905 : " + validatePhoneNumber("123-567-8905"));
  System.out.println("Validation for 9866767545 : " + validatePhoneNumber("9866767545"));
  System.out.println("Validation for 123-456-7890 ext9876 : " + validatePhoneNumber("123-456-7890 ext9876"));

And the outputs:

Validation for 1234567890 : true
Validation for 1234 567 890 : true
Validation for 123 456 7890 : true
Validation for 123-567-8905 : true
Validation for 9866767545 : true
Validation for 123-456-7890 ext9876 : true

For more info please refer to this link.

Abbas Jafari
  • 1,492
  • 2
  • 16
  • 28
0

Try this function it should work.

fun isValidPhone(phone: String): Boolean =
    phone.trimmedLength() in (10..13) && Patterns.PHONE.matcher(phone).matches()
RJnr
  • 670
  • 6
  • 19
-1

You shouldn't be using Regular Expressions when validating phone numbers. Check out this JSON API - numverify.com - it's free for a nunver if calls a month and capable of checking any phone number. Plus, each request comes with location, line type and carrier information.

Jess
  • 27
  • 4