I am using the following code to validate a phone number. The requirements are the phone number should be inbetween 10-25 characters length, should include hypen(-),period(.), parentheses ().
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePhoneNumber {
public static void main(String[] argv) {
String phoneNumber = "6058.8()6-05888,9994567";
System.out.println(phoneNumber.length());
//String sPhoneNumber = "605-88899991";
//String sPhoneNumber = "605-888999A";
String regex = "^[0-9.()-]{10,25}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(phoneNumber);
if (matcher.matches()) {
System.out.println("Phone Number Valid");
} else {
System.out.println("Phone Number must be in the form XXX-XXXXXXX");
}
}
}
I checked the validations and its working fine, I want to add a whitespace character “\s” as well so that in between the phone number there can be whitespace as well. But getting errors while adding “\s” in regex.
Please, look at standards like ITU E.164 or IETF RfC 3966. Don’t assume that every country has the same conventions and number lengths.
Here’s the relevant ABNF part out of RfC 3966
We recently had a huge trouble with a device that didn’t let the user enter the ‘+’ as part of a phone number.