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
  • 311
  • 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,129
  • 2
  • 33
  • 80
Aniruddha
  • 4,477
  • 2
  • 21
  • 39
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
  • 5,350
  • 4
  • 28
  • 38
-2
private boolean isValidphone(String bphone) {
    return !TextUtils.isEmpty(bphone) && 
    bphone.length() == 10 && 
    TextUtils.isDigitsOnly(bphone);
}
MEGHA DOBARIYA
  • 1,622
  • 9
  • 7