I need to validate the beginning of a phone number, by this I mean I need to make sure that a country code was provided. The phone number should start with a plus sign followed by a minimum of 1 number and a maximum of 3 numbers followed by a hyphen.
Example of valid numbers...
+1-555-5555
+12-5555555
+123-(555) 555-5555
Examples of an invalid phone number
+1(555) 555-5555
5555555555
+5555555555
This is what I have so far. What I'm doing is stripping all non-digits to verify that I have a minimum of 10 numbers. I then verify that I have a country code of a minimum of 3 numbers. After that, if the phone number doesn't begin with a "+", I prepend one.
private boolean isPhoneNumberValid(String phoneNumber) {
if (!isPhoneNumberLengthValid(phoneNumber) || !isCountryCodeLenghtValid(phoneNumber)) {
return false;
}
if (!phoneNumber.startsWith("+")) {
request.getDestination().setMobilePhoneNumber("+" + phoneNumber);
}
return true;
}
private boolean isPhoneNumberLengthValid(String phoneNumber) {
return phoneNumber.replaceAll("\\D+","").length() < 10;
}
private boolean isCountryCodeLenghtValid(String phoneNumber) {
String countryCode = StringUtils.left(phoneNumber, phoneNumber.indexOf("-")).replaceAll("\\D+","");
return countryCode.length() >= 1 && countryCode.length() <= 3;
}
What is the best way of validating the country code?