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
๐ŸŒ
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
๐ŸŒ
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 17.9K 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%
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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"};
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
Java2Blog
java2blog.com โ€บ home โ€บ core java โ€บ validation โ€บ validate phone number in java
Validate phone number in java - Java2Blog
January 11, 2021 - (?: โ€“> Group but donโ€™t capture: [0-9] โ€“> Match a digit from 0-9. \x20 โ€“> Match a space character(used x20 to show space character) ? โ€“> between zero and one time. ) โ€“> End the noncapturing group. {6,14} โ€“> Recur the group between 6 and 14 times. [0-9] โ€“> Match digit from 0-9 $ โ€“> Assert position at the end of the string. ... +91 3423 546443 is valid phone number +44 343 2324 is valid phone number 91 4354 3454 is invalid Phone number
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.