To validate the Phone Number in Java it’s better to use regular expressions. Here I have explained some Regular expressions concepts to validate the phone numbers.
First Fore users to enter at least 5 digit number and max 13-14 digits.
Explanation
\\d = only digit allow
{3} = length
All phone numbers must in “xx-xxxxxxxxx” format. For example
phone number validation in Java source code below
public void matchPhoneNumbers() {
String patterns
= "^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"
+ "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$"
+ "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$";
//Example no's below please replace with your input value and remove for loop, its added just to show example.
String[] validPhoneNumbers
= {"6739827465","673 982 7465", "(673) 982-7465", "+111 (673) 982-7465",
"636 856 789", "+111 636 856 789", "636 85 67 89", "+111 636 85 67 89"};
Pattern pattern = Pattern.compile(patterns);
for(String phoneNumber : validPhoneNumbers) {
Matcher matcher = pattern.matcher(phoneNumber);
assertTrue(matcher.matches());
}
}
Arjun is a Full-stack developer, who is fond of the web. Lives in Chikmagalur, Karnataka, India