-3

I have a generic phone number validation function that currently validates all global phone numbers. I wanted to update it so that it only validates US phone numbers. But the problem with that is currently even if i set my phone number length to 10, it will stop short at exactly 10 characters. my users may enter something like a space or a ( ,for example : "(444)444 4444 , which wont work if i limit the number of chars to 10 even if its a valid number.Any ideas how to go about it? here's my function :

public static boolean isValidPhoneNumber(String phoneNumber) {
    return !TextUtils.isEmpty(phoneNumber) && android.util.Patterns.PHONE.matcher(phoneNumber).matches() && PhoneNumberUtils.;
}
Khojiakbar
  • 559
  • 5
  • 14
  • Post your code relevant to your explanation for updating existing code. – Ravi Apr 05 '19 at 15:19
  • I would recommend using `TextWatcher` for this kind of things. – Khojiakbar Apr 05 '19 at 15:20
  • @Ravi i have. check my question –  Apr 05 '19 at 15:21
  • @Khojiakbar how does a textwatcher help in this case? –  Apr 05 '19 at 15:22
  • @MarissaNicholas You can look at this post to make your own `TextWatcher` that will format text as you want https://stackoverflow.com/questions/16975304/automatically-add-dash-in-phone-number-in-android – Khojiakbar Apr 05 '19 at 15:25
  • How do the users set their phone numbers? If you use an EditText for that add the attribute android:inputType="phone" on the layout and the users will only be able to enter numbers. – Nikos Hidalgo Apr 05 '19 at 15:52

1 Answers1

0

The best way i think would be to use https://github.com/MichaelRocks/libphonenumber-android.

You can include it in your project as following:

repositories {
  jcenter()
}

dependencies {
  implementation 'io.michaelrocks:libphonenumber-android:8.10.7'
} 

And then use it like:

public void validateNumber(View view) {
        PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.createInstance(this);
        Phonenumber.PhoneNumber phoneNumber = null;
        try {

            phoneNumber = phoneNumberUtil.parse("(541) 754-3010"/*replace with your number*/, "US");
            boolean isValid = phoneNumberUtil.isValidNumber(phoneNumber);
            Toast.makeText(this, "" + isValid, Toast.LENGTH_SHORT).show();
        } catch (NumberParseException e) {
            e.printStackTrace();
        }
    }
Mayur Gajra
  • 8,285
  • 6
  • 25
  • 41