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