0

I have an EditText defined in layout xml like this:

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:id="@+id/enter_phone_field"
        android:layout_below="@id/enter_name_field"
        android:layout_alignRight="@id/destination_value_label"
        android:layout_alignEnd="@id/destination_value_label" />

I have implemented its OnFocusChangeListener like this:

enterPhoneNumber = (EditText)findViewById(R.id.enter_phone_field);


        // phone number lost focus listener
        enterPhoneNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus){
                    if (PhoneNumberUtils.isGlobalPhoneNumber(enterPhoneNumber.getText().toString())){
                        //valid phone number detected
                        Log.i("PhoneNumberValidated", enterPhoneNumber.getText().toString());
                    }
                    else {
                        enterPhoneNumber.setError("Please enter valid phone number");
                    }
                }
            }
        });

I tried entering 34 in enterPhoneNumber field, and when I tapped out of it for some reasons it did not show error on it.

Any ideas?

Devarshi
  • 16,440
  • 13
  • 72
  • 125
  • Do you need it to be global phone number method? – Stanojkovic Feb 10 '16 at 19:31
  • @Stanojkovic is there any other alternative? Basically I am trying to validate an Indian phone number, the number which may not have country code as prefix, without country code its length is 10 digits – Devarshi Feb 11 '16 at 13:25
  • 1
    This is how I solve that: String regexStr = "^[+][0-9]{11,12}$"; if (!number.matches(regexStr)){do your stuff here, AlertDialog or some warning}, you just need to change how much numbers you want to check. – Stanojkovic Feb 11 '16 at 19:25
  • You could check number on your `setOnFocusChangeListener()` method. – Stanojkovic Feb 11 '16 at 20:18

1 Answers1

0

Because "34" is global number by definition of the PhoneNumberUtils.isGlobalPhoneNumber which in its turn checks that "34" matches the pattern:

private static final Pattern GLOBAL_PHONE_NUMBER_PATTERN =
            Pattern.compile("[\\+]?[0-9.-]+");
MikeL
  • 5,385
  • 42
  • 41
  • is there any other alternative? Basically I am trying to validate an Indian phone number, the number which may not have country code as prefix, without country code its length is 10 digits – Devarshi Feb 11 '16 at 13:26