Phone number validation Android
Asked Answered
B

16

77

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

Butler answered 15/6, 2011 at 13:25 Comment(1)
I think you get your answer from here. https://mcmap.net/q/267484/-email-and-phone-number-validation-in-androidSaez
C
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}$
Clasp answered 15/6, 2011 at 13:55 Comment(12)
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.Clasp
Its taking other special characters also...wen is used ^/+[0-9]{10,13}$Butler
forward slash is wrong; I specified back slash. But try the alternative string I suggested as well.Clasp
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}$Butler
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?Clasp
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 +.Butler
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....Clasp
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?Butler
no, you should only need one regex: the question mark makes the + optional. See my last edit to the answer.Clasp
Its working nice for me. Thanks.. But I used the approach of Pattern.matcher and Pattern.compile(), which are easier to use.Deus
what will be the regex for only 10 digit without +91 ?Buddhology
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}$.Waldner
W
135

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.

Whittier answered 15/6, 2011 at 14:15 Comment(12)
This is a WAY better answer than the others!Cathicathie
I am using (!PhoneNumberUtils.isGlobalPhoneNumber("1234")), then also its taking as a valid number. Where actually its not. What should I do?Deus
@Deus you need to mention the 'Valid' number. For someone to help you. Or post another question.Culpepper
Note that isGlobalPhoneNumber will return false for formats such as (123) 456-7890 (whereas 123-456-7890 will return true)Emlynn
Phone numbers that contain * are also returned as invalidWirework
Does not work for india +919953617447 or 9953617447 or +91-9953617447..thought u shld knwHann
Doesn't work! Returns true for local number 0503701329. Really not reliable solutionWilltrude
This method isn't reliable. It's returning true for numbers that contain * and even 53123123Overjoy
Method is not reliableIsomerize
Always run PhoneNumberUtils.stripSeparators() first to get only the "+" and digitsSalt
I don't recommend this. It says "1" is a valid global phone numberInenarrable
This not reliable. ".................." is a valid number.Octahedron
C
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}$
Clasp answered 15/6, 2011 at 13:55 Comment(12)
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.Clasp
Its taking other special characters also...wen is used ^/+[0-9]{10,13}$Butler
forward slash is wrong; I specified back slash. But try the alternative string I suggested as well.Clasp
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}$Butler
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?Clasp
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 +.Butler
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....Clasp
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?Butler
no, you should only need one regex: the question mark makes the + optional. See my last edit to the answer.Clasp
Its working nice for me. Thanks.. But I used the approach of Pattern.matcher and Pattern.compile(), which are easier to use.Deus
what will be the regex for only 10 digit without +91 ?Buddhology
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}$.Waldner
K
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;
}
Keep answered 17/3, 2015 at 20:33 Comment(9)
You can also do phoneUtil.parse(phonePrefix + phoneNumber, null) if you don't have the region.Prudie
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 digitMatthia
Also make sure that number which you validate starts from '+'Willtrude
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.Inenarrable
How do you even integrate this library?Farwell
@Farwell 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.Keep
Thanks. I was able to figure it out.Farwell
To integrate this library, insert implementation group: 'com.googlecode.libphonenumber', name: 'libphonenumber', version: '8.4.2' to your Gradle.Duly
The Android port for this lib github.com/MichaelRocks/libphonenumber-androidInterspace
C
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.
Cupronickel answered 15/5, 2014 at 10:33 Comment(4)
This returns true if it looks like a phone number not sure it validates if it is actually a phone number. Source: developer.android.com/reference/android/util/Patterns.htmlOrphrey
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).Tangram
I like this Pattern, it also has validation for email and a lot of other useful patterns.Impaste
"…not for validating whether something is in fact a phone number."Splinter
M
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();
        }

    }
Meadows answered 17/7, 2015 at 12:40 Comment(2)
public final static boolean isValidPhoneNumber(CharSequence phone) { return phone != null && !(phone.length() < 6 || phone.length() > 13) && android.util.Patterns.PHONE.matcher(phone).matches(); }Disqualification
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."Milklivered
M
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

Manganese answered 10/1, 2018 at 18:39 Comment(1)
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.Welloff
K
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.

Katz answered 15/6, 2011 at 13:36 Comment(1)
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.Cambridge
F
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();
    }

}
Fichu answered 19/10, 2016 at 9:11 Comment(1)
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. developer.android.com/reference/android/util/…Bergren
N
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();
            }
Namara answered 15/7, 2018 at 15:17 Comment(0)
U
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} 
Unappealable answered 3/4, 2020 at 10:11 Comment(1)
Good explanation on each part of the block of the Pattern. This should be the accepted answer.Zany
F
1
^\+201[0|1|2|5][0-9]{8}

this regex matches Egyptian mobile numbers

Fading answered 26/6, 2019 at 19:43 Comment(0)
V
0

Here is how you can do it succinctly in Kotlin:

fun String.isPhoneNumber() =
            length in 4..10 && all { it.isDigit() }
Verb answered 9/8, 2018 at 4:3 Comment(1)
This is nice and concise code, however, it's not a comprehensive check for phone number validity in general. See here: github.com/googlei18n/libphonenumber/blob/master/FALSEHOODS.mdAnyplace
I
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

Infancy answered 29/3, 2019 at 11:10 Comment(0)
E
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.

Elaterite answered 10/3, 2021 at 10:0 Comment(0)
H
0

Try this function it should work.

fun isValidPhone(phone: String): Boolean =
    phone.trimmedLength() in (10..13) && Patterns.PHONE.matcher(phone).matches()
Hemlock answered 28/5, 2022 at 13:11 Comment(0)
T
-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.

Turaco answered 3/10, 2015 at 10:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.