2

How to validate phone number in EditText for Android?

I tried using this code:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:ems="10"
    android:id="@+id/editText"
   />

But it will not work for special characters. Any help?

Deepak Keynes
  • 301
  • 2
  • 16
  • 1
    possible duplicate of [Email and phone Number Validation in android](http://stackoverflow.com/questions/22505336/email-and-phone-number-validation-in-android) – Shabbir Dhangot Apr 30 '15 at 04:59

3 Answers3

2

Try this Method:

private boolean isValidPhoneNumber(String phone) {

    if (!phone.trim().equals("") && phone.length() > 10) {
            return Patterns.PHONE.matcher(phone).matches();
    }

        return false;
}
Alireza Noorali
  • 3,777
  • 2
  • 26
  • 71
Aniruddha
  • 4,457
  • 1
  • 20
  • 38
0

So far, this is the best solution I have found to validate a phone number (code in Kotlin, extension of String)

fun String.isValidPhoneNumber() : Boolean {
    val patterns =  "^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$"
    return Pattern.compile(patterns).matcher(this).matches()
}
Sean Blahovici
  • 3,852
  • 3
  • 23
  • 31
-2
private boolean isValidphone(String bphone) {
    return !TextUtils.isEmpty(bphone) && 
    bphone.length() == 10 && 
    TextUtils.isDigitsOnly(bphone);
}
MEGHA DOBARIYA
  • 1,506
  • 8
  • 5