All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.nls.util.PhoneUtil Maven / Gradle / Ivy

There is a newer version: 1.0.14
Show newest version
package com.nls.util;

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

public final class PhoneUtil {
    private static final PhoneNumberUtil INSTANCE = PhoneNumberUtil.getInstance();

    private PhoneUtil() {
    }

    public static boolean valid(String phoneRaw) {
        if (phoneRaw == null || phoneRaw.isEmpty()) {
            return false;
        }

        try {
            Phonenumber.PhoneNumber phone = INSTANCE.parse(phoneRaw, "GB");
            return INSTANCE.isValidNumber(phone);
        } catch (NumberParseException e) {
            return false;
        }
    }

    public static String normalise(String phoneRaw) {
        if (!valid(phoneRaw)) {
            return phoneRaw == null ? null : phoneRaw.replaceAll(" ", "");
        }

        return prettify(phoneRaw).replaceAll(" ", "");
    }

    public static String prettify(String phoneRaw) {
        if (phoneRaw == null || phoneRaw.isEmpty() || !valid(phoneRaw)) {
            return phoneRaw;
        }

        try {
            Phonenumber.PhoneNumber phone = INSTANCE.parse(phoneRaw, "GB");
            return  phone.getCountryCode() == 44
                    ? INSTANCE.format(phone, PhoneNumberUtil.PhoneNumberFormat.NATIONAL)
                    : INSTANCE.format(phone, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
        } catch (NumberParseException ignore) {
            return phoneRaw;
        }
    }

    public static String prettify(String phoneRaw, String defaultRegion) {
        if (phoneRaw == null || phoneRaw.isEmpty() || !valid(phoneRaw)) {
            return phoneRaw;
        }

        try {
            Phonenumber.PhoneNumber phone = INSTANCE.parse(phoneRaw, defaultRegion);
            return INSTANCE.format(phone, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
        } catch (NumberParseException ignore) {
            return phoneRaw;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy