You can use simple String.matches(regex) to test any string against a regex pattern instead of using Pattern and Matcher classes.

Sample:

boolean isValid = phoneString.matches(regexPattern);

Find more examples

Here is the regex pattern as per your input string:

\+\d(-\d{3}){2}-\d{4}

Online demo


Better use Spring validation annotation for validation.

Example

Answer from Braj on Stack Overflow
Top answer
1 of 9
6

You can use simple String.matches(regex) to test any string against a regex pattern instead of using Pattern and Matcher classes.

Sample:

boolean isValid = phoneString.matches(regexPattern);

Find more examples

Here is the regex pattern as per your input string:

\+\d(-\d{3}){2}-\d{4}

Online demo


Better use Spring validation annotation for validation.

Example

2 of 9
4
// The Regex not validate mobile number, which is in internation format.
// The Following code work for me. 
// I have use libphonenumber library to validate Number from below link.
// http://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/8.0.1/
//  https://github.com/googlei18n/libphonenumber
// Here, is my source code.

 public boolean isMobileNumberValid(String phoneNumber)
    {
        boolean isValid = false;

        // Use the libphonenumber library to validate Number
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        Phonenumber.PhoneNumber swissNumberProto =null ;
        try {
            swissNumberProto = phoneUtil.parse(phoneNumber, "CH");
        } catch (NumberParseException e) {
            System.err.println("NumberParseException was thrown: " + e.toString());
        }

        if(phoneUtil.isValidNumber(swissNumberProto))
        {
            isValid = true;
        }

        // The Library failed to validate number if it contains - sign
        // thus use regex to validate Mobile Number.
        String regex = "[0-9*#+() -]*";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNumber);

        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }
🌐
Baeldung
baeldung.com › home › java › validate phone numbers with java regex
Validate Phone Numbers With Java Regex | Baeldung
January 8, 2024 - Learn how to validate different formats of phone numbers using regular expressions.
🌐
How to do in Java
howtodoinjava.com › home › java regular expressions › regex for north american phone number validation
Regex for North American Phone Number Validation
February 16, 2026 - I have tested formats including 1234567890, 123-456-7890, 123.456.7890, 123 456 7890, (123) 456 7890, and all such combinations. Regex : ^\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$ The above regular expression can be used to validate all formats of phone numbers to check if they are valid North American phone numbers.
🌐
AbstractAPI
abstractapi.com › api guides, tips & tricks › java phone number validation guide
How to Validate Phone Numbers Effectively in Java (2024)
June 11, 2025 - Master Java phone number validation: Learn to use regex, validate US/Indian numbers, and integrate Abstract's API for precise, reliable results.
🌐
Javaprogramto
javaprogramto.com › 2020 › 04 › java-phone-number-validation.html
How To Validate Phone Numbers in Java (Regular Expression + Google libphonenumber) JavaProgramTo.com
July 10, 2020 - The main advantage of this API is that you can format or validate and parse any country or region mobile numbers. Class PhoneNumberUtil is a utility for international phone numbers.
🌐
Mkyong
mkyong.com › home › java › how to validate phone number in java (regular expression)
How to validate phone number in Java (regular expression) - Mkyong.com
August 30, 2012 - Not everyone in the world has the same style phone number. ... Try understand the concept, and you can customize it to any use case. ... I am trying to validate US phone number in the form of 555-555-5555 and its working fine and if this is not matching its giving error message is fine.
🌐
TutorialsPoint
tutorialspoint.com › phone-number-validation-using-java-regular-expressions
Phone Number validation using Java Regular Expressions
Following example shows how to match phone numbers in a list to a particle pattern by using phone.matches(phoneNumberPattern) method. public class MatchPhoneNumber { public static void main(String args[]) { isPhoneValid("1-999-585-4009"); isPhoneValid("999-585-4009"); isPhoneValid("1-585-4009"); isPhoneValid("585-4009"); isPhoneValid("1.999-585-4009"); isPhoneValid("999 585-4009"); isPhoneValid("1 585 4009"); isPhoneValid("111-Java2s"); } public static boolean isPhoneValid(String phone) { boolean retval = false; String phoneNumberPattern = "(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}"; retval = phone.matches(phoneNumberPattern); String msg = "NO MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern; if (retval) { msg = " MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern; } System.out.println(msg + "\r\n"); return retval; } }
🌐
Java67
java67.com › 2020 › 04 › how-to-validate-phone-number-in-java.html
How to validate phone numbers in Java? Google libphonenumber library Example Tutorial | Java67
Unfortunately, Java doesn't provide ... right? Yes, there is Google's phone number library which allows you to validate any phone number both international, USA specific, or any country-specific....
Find elsewhere
🌐
GitHub
github.com › google › libphonenumber
GitHub - google/libphonenumber: Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers. · GitHub
Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers. The Java version is optimized for running on smartphones, and is used by the Android framework since 4.0 (Ice Cream Sandwich).
Starred by 18K users
Forked by 2.2K users
Languages   C++ 53.4% | Java 29.9% | JavaScript 15.8% | CMake 0.4% | C 0.2% | Closure Templates 0.1%
🌐
Stack Abuse
stackabuse.com › java-regular-expressions-validate-phone-number
Java Regular Expressions - Validate Phone Number
November 23, 2021 - In this short article, we'll take a look at how to validate a phone number in Java, using the regex package and multiple Regular Expressions.
🌐
UI Bakery
uibakery.io › regex-library › phone-number-java
Phone number regex Java
The regular expressions below can be used to validate if a string is a valid phone number format and to extract a phone number from a string. Please note that this validation can not tell if a phone number actually exists. ... A simple regex to validate string against a valid international phone number format without delimiters and with an optional plus sign: ... import java.util.regex.Pattern; import java.util.regex.MatchResult; public class Main { public static void main(String []args) { // Validate phone number boolean isMatch = Pattern.compile("^\\+?[1-9][0-9]{7,14}$") .matcher("+122233344
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-check-for-a-valid-mobile-number
Java Program to Check For a Valid Mobile Number - GeeksforGeeks
July 23, 2025 - // Java program to Validating Global Mobile Numbers import java.util.regex.*; public class GFG { // Method to check if mobile number is valid public static boolean isValid(String s) { // Regular expression to validate // global mobile numbers ...
🌐
Java Code Geeks
javacodegeeks.com › home › core java
How To Validate Phone Numbers in Java (Regular Expression + Google libphonenumber) - Java Code Geeks
April 27, 2020 - A quick guide to how to validate phone numbers in java for different countries such as the USA, IN.
🌐
Baeldung
baeldung.com › home › java › using libphonenumber for phone number validation and conversion
Using libphonenumber for Phone Number Validation and Conversion | Baeldung
November 24, 2025 - In this quick tutorial, we’ll see how to use Google’s open-source library libphonenumber to validate phone numbers in Java.
🌐
w3resource
w3resource.com › java-exercises › re › java-re-exercise-22.php
Java - Validate a given phone number
Write a Java program to validate a phone number. Following are valid phone number examples: “(123)4567890", "1234567890", "123-456-7890", "(123)456-7890", Following are invalid phone numbers: "(1234567890)","123)4567890", "12345678901", "(1)234567890", "(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};
🌐
GitHub
gist.github.com › sangramanand › 1892516
Validating phone number using Java · GitHub
February 23, 2012 - Save sangramanand/1892516 to your computer and use it in GitHub Desktop. ... 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 ... The regex code accepts a phone number between 10-25 chars length.
🌐
Medium
medium.com › @dfs.techblog › contact-number-normalization-in-java-5073c31d8100
Contact Number Normalization in Java | by Comviva MFS Engineering Tech Blog | Medium
January 31, 2025 - By using libphonenumber, you can easily parse, validate, and format phone numbers in a standardized way, reducing errors, improving data quality, and ensuring compatibility with external services.
🌐
Twilio
twilio.com › en-us › blog › validating-phone-numbers-spring-boot-twilio-lookup-api
Validating phone numbers in a Spring Boot app using the Twilio Lookup API | Twilio
June 18, 2025 - There are multiple levels of validation possible - in this post I’ll show how to use the Twilio Lookup API to check if a real phone number is real. The demo application will use Spring Boot and I will show how to use the Bean Validation framework to create a @ValidPhoneNumber annotation that can be used like you would @NotNull. ... A Twilio account. Sign up using this link and you can get an extra $10 credit when you upgrade your account. Java installed - use Java 8 or newer.
Top answer
1 of 4
3

If this is not homework, is there a reason you're avoiding regular expressions?

Here are some useful ones: http://regexlib.com/DisplayPatterns.aspx?cattabindex=6&categoryId=7

More generally, your code doesn't seem to validate that you have a phone number, it seems to merely validate that your strings consists only of digits. You're also not allowing any special characters right now.

2 of 4
1

Asides from the regex suggestion (which is a good one), it would seem to make more sense to deal with arrays of characters rather than single-char Strings.

In particular, the split("") call (shudder) could/should be replaced by toCharArray(). This lets you iterate over each individual character, which more clearly indicates your intent, is less prone to bugs as you know you're treating each character at once, and is more efficient*. Likewise your valid character sets should also be characters.

Your logic is pretty strangely expressed; you're not even referencing the specialChars set at all, and the looping logic once you've found a match seems odd. I think this is your bug; the matching seems to be the wrong way round in that if the character matches the first valid char, you set flag to false and continue round the current loop; so it will definitely not match the next valid char and hence you break out of the loop with a true flag. Always.

I would have thought something like this would be more intuitive:

private static final Set<Character> VALID_CHARS = ...;

public boolean isValidPhoneNumber(String number)
{
    for (char c : number,toCharArray())
    {
        if (!VALID_CHARS.contains(c))
        {
           return false;
        }
    }

    // All characters were valid
    return true;
}

This doesn't take sequences into account (e.g. the strings "--------** " and "1" would be valid because all individual characters are valid) but then neither does your original code. A regex is better because it lets you specify the pattern, I supply the above snippet as an example of a clearer way of iterating through the characters.

*Yes, premature optimization is the root of all evil, but when better, cleaner code also happens to be faster that's an extra win for free.