Validate Phone Number in Android using libphonenumber Library

Validating International Phone Number by your own code is not simple because different country uses different
  • number of digits
  • country code
  • format of phone numbers
We are going to use Google's library libphonenumber. This can be used for parsing, formatting, storing and validating phone numbers. This library is being supported by Android framework since 4.0 (Ice Cream Sandwich).

Validate Phone Number Sample Program Layout
Sample Program Layout


More information on Google's library libphonenumber

To include in your project download the latest Jars from GitHub by clicking on below link
http://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/

In your Android Studio
go to File and click on Project Structure
select Dependencies Tab then
click on Add button then select File dependency
select downloaded Jar file

Sample Program:
In addition of libphonenumber, android method isValidPhoneNumber(phoneNumber) is used because passing null or 1 to 2 digit phone number directly to current version of  libphonenumber 7.2.1 crashing the app.

activity_main.xml (Layout File)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edtCountryCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:hint="@string/country_code"/>

    <EditText
        android:id="@+id/edtPhoneNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/edtCountryCode"
        android:inputType="phone"
        android:hint="@string/phone_no"/>

    <TextView
        android:id="@+id/tvIsValidPhone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edtPhoneNumber"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"/>

    <Button
        android:id="@+id/btnValidate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvIsValidPhone"
        android:text="@string/validate"/>

</RelativeLayout>

MainActivity.java
package com.sonevalley.tech.phonevalidation;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;

public class MainActivity extends AppCompatActivity {

    TextView tvIsValidPhone;
    EditText edtPhone;
    EditText edtCountryCode;
    Button btnValidate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvIsValidPhone = (TextView) findViewById(R.id.tvIsValidPhone);
        edtCountryCode = (EditText) findViewById(R.id.edtCountryCode);
        edtPhone = (EditText) findViewById(R.id.edtPhoneNumber);
        btnValidate = (Button) findViewById(R.id.btnValidate);
        btnValidate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String countryCode = edtCountryCode.getText().toString().trim();
                String phoneNumber = edtPhone.getText().toString().trim();
                if(countryCode.length() > 0 && phoneNumber.length() > 0){
                    if(isValidPhoneNumber(phoneNumber)){
                        boolean status = validateUsing_libphonenumber(countryCode, phoneNumber);
                        if(status){
                            tvIsValidPhone.setText("Valid Phone Number (libphonenumber)");
                        } else {
                            tvIsValidPhone.setText("Invalid Phone Number (libphonenumber)");
                        }
                    }
                    else {
                        tvIsValidPhone.setText("Invalid Phone Number (isValidPhoneNumber)");
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Country Code and Phone Number is required", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private boolean isValidPhoneNumber(CharSequence phoneNumber) {
        if (!TextUtils.isEmpty(phoneNumber)) {
            return Patterns.PHONE.matcher(phoneNumber).matches();
        }
        return false;
    }

    private boolean validateUsing_libphonenumber(String countryCode, String phNumber) {
        PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
        String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(countryCode));
        Phonenumber.PhoneNumber phoneNumber = null;
        try {
            //phoneNumber = phoneNumberUtil.parse(phNumber, "IN");  //if you want to pass region code
            phoneNumber = phoneNumberUtil.parse(phNumber, isoCode);
        } catch (NumberParseException e) {
            System.err.println(e);
        }

        boolean isValid = phoneNumberUtil.isValidNumber(phoneNumber);
        if (isValid) {
            String internationalFormat = phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
            Toast.makeText(this, "Phone Number is Valid " + internationalFormat, Toast.LENGTH_LONG).show();
            return true;
        } else {
            Toast.makeText(this, "Phone Number is Invalid " + phoneNumber, Toast.LENGTH_LONG).show();
            return false;
        }
    }
}

Library libphonenumber also provides other features such as if you want to know weather a particular phone number is mobile number or fixed line number.
PhoneNumberUtil.PhoneNumberType isMobile = phoneNumberUtil.getNumberType(phoneNumber);
if(PhoneNumberUtil.PhoneNumberType.MOBILE==isMobile){
 Toast.makeText(this, "Mobile Number is Valid " + internationalFormat, Toast.LENGTH_LONG).show();
}
else if(PhoneNumberUtil.PhoneNumberType.FIXED_LINE==isMobile){
 Toast.makeText(this, "Fixed Line is Valid " + internationalFormat, Toast.LENGTH_LONG).show();
}

Preview Screens:
Validate Phone Number Sample Program Screenshot
Validate Phone Number Screenshot

Validate Phone Number Sample Program Screenshot
Validate Phone Number Screenshot


SHARE
    Blogger Comment
    Facebook Comment

9 comments:

  1. app crashes on entering more than 3 digits in phone number

    ReplyDelete
  2. I'm not familiar with JAR files, there are tonnes of files on that link. which files exactly do we download?

    ReplyDelete
  3. To download JAR file, I chosen latest version 8.7.0 from the given link, downloaded libphonenumber-8.7.0.jar and it worked perfectly for me.

    ReplyDelete
  4. Great tutorial, thanks so much.

    By the way the JAR file , it didn't work for me. I use this in Android Studio :
    compile 'com.googlecode.libphonenumber:libphonenumber:8.4.2'

    ReplyDelete
  5. Thanks for this great tutorial. Work for me...

    ReplyDelete
  6. https://github.com/MichaelRocks/libphonenumber-android

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Thanks for this glorious article. Also a thing is that the majority of digital cameras can come equipped with any zoom lens so that more or less of that scene to generally be included through ‘zooming’ in and out. These types of changes in focusing length will be reflected inside the viewfinder and on significant display screen on the back of any camera.
    Email Validation Software | Valid Email Address Checker

    ReplyDelete