001
014
015 package com.liferay.util.format;
016
017 import com.liferay.portal.kernel.format.PhoneNumberFormat;
018 import com.liferay.portal.kernel.util.PropsKeys;
019 import com.liferay.portal.kernel.util.PropsUtil;
020 import com.liferay.portal.kernel.util.StringBundler;
021 import com.liferay.portal.kernel.util.StringPool;
022 import com.liferay.portal.kernel.util.StringUtil;
023 import com.liferay.portal.kernel.util.Validator;
024
025
031 public class USAPhoneNumberFormat implements PhoneNumberFormat {
032
033 @Override
034 public String format(String phoneNumber) {
035 if (Validator.isNull(phoneNumber)) {
036 return StringPool.BLANK;
037 }
038
039 if (phoneNumber.length() > 10) {
040 StringBundler sb = new StringBundler(8);
041
042 sb.append(StringPool.OPEN_PARENTHESIS);
043 sb.append(phoneNumber.substring(0, 3));
044 sb.append(") ");
045 sb.append(phoneNumber.substring(3, 6));
046 sb.append(StringPool.DASH);
047 sb.append(phoneNumber.substring(6, 10));
048 sb.append(" x");
049 sb.append(phoneNumber.substring(10));
050
051 return sb.toString();
052 }
053 else if (phoneNumber.length() == 10) {
054 StringBundler sb = new StringBundler(6);
055
056 sb.append(StringPool.OPEN_PARENTHESIS);
057 sb.append(phoneNumber.substring(0, 3));
058 sb.append(") ");
059 sb.append(phoneNumber.substring(3, 6));
060 sb.append(StringPool.DASH);
061 sb.append(phoneNumber.substring(6));
062
063 return sb.toString();
064 }
065 else if (phoneNumber.length() == 7) {
066 return phoneNumber.substring(0, 3).concat(StringPool.DASH).concat(
067 phoneNumber.substring(3));
068 }
069
070 return phoneNumber;
071 }
072
073 @Override
074 public String strip(String phoneNumber) {
075 return StringUtil.extractDigits(phoneNumber);
076 }
077
078 @Override
079 public boolean validate(String phoneNumber) {
080 if (Validator.isNull(phoneNumber)) {
081 return false;
082 }
083
084 return phoneNumber.matches(
085 PropsUtil.get(PropsKeys.PHONE_NUMBER_FORMAT_USA_REGEXP));
086 }
087
088 }