Created
July 21, 2020 11:24
-
-
Save jaredpalmer/c552166ce68f9963b38e6d48a42b7a64 to your computer and use it in GitHub Desktop.
US Phone Validation w/ext
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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