how i can use metod to valdiate mobile numbers { 011xxxxxxxx and012xxxxxxxxand010xxxxxxxx}

String MobilePattern = "[0-9]{10}";
            if (mobile_number.length() != 11 && 
 !mobile_number.getText().toString().matches(MobilePattern) ) {

                mobile_number.setError("Please Enter correct mobile number");
                return;
            }

how i can use metod to valdiate mobile numbers { 011xxxxxxxx and 012xxxxxxxx and 010xxxxxxxx}

2 answers

  • answered 2017-06-17 18:10 Dany Poplawec

    Try this with PhoneNumberUtil class:

    package com.google.i18n.phonenumbers;
    
    public static boolean isNumberValid(String countryCode, String phNumber) {
        if (TextUtils.isEmpty(countryCode)) {// Country code could not be empty
            return false;
        }
        if (phNumber.length() < 6) {        // Phone number should be at least 6 digits
            return false;
        }
        boolean resultPattern = Patterns.PHONE.matcher(phNumber).matches();
        if (!resultPattern) {
            return false;
        }
    
        PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
        String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(countryCode));
        Phonenumber.PhoneNumber phoneNumber = null;
        try {
            phoneNumber = phoneNumberUtil.parse(phNumber, isoCode);
        } catch (NumberParseException e) {
            return false;
        }
    
        return phoneNumberUtil.isValidNumber(phoneNumber);
    }
    

    Where countryCode is the dialcode of a country : 33 for France , 34 for Spain etc...

  • answered 2017-06-17 18:10 Ibrahim

    You can check if number start with values you need or no, ex :

    String mob = mobile_number.getText().toString();
    
    if(mob.startsWith("010") || mob.startsWith("011") || mob.startWith("012")){
    
          //todo your logic here 
    
      }