Skip to content

Instantly share code, notes, and snippets.

@jaredpalmer
Created July 21, 2020 11:24
Show Gist options
  • Save jaredpalmer/c552166ce68f9963b38e6d48a42b7a64 to your computer and use it in GitHub Desktop.
Save jaredpalmer/c552166ce68f9963b38e6d48a42b7a64 to your computer and use it in GitHub Desktop.
US Phone Validation w/ext
package org.formium.util;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import java.util.Optional;
public class ValidateUtil {
public static Optional<String> validatePhone(String phone) {
if (phone == null) {
return Optional.empty();
}
phone = phone.trim();
if ("".equals(phone)) {
return Optional.empty();
}
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
Phonenumber.PhoneNumber number = phoneUtil.parse(phone, "US");
String ext = number.getExtension().length() > 0 ? ";ext=" + number.getExtension() : "";
return Optional.of(phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164) + ext);
} catch (NumberParseException e) {
return Optional.empty();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment