In this Java tutorial, you will learn how to validate a phone number using String.matches() and regular expressions. You will also learn the limits of regex-based phone validation and when a dedicated phone-number library is more appropriate.

Validate a Phone Number in Java with String.matches()

If your application expects a specific phone-number format, you can describe that format with a regular expression and test the input using String.matches().

For example, a requirement such as “three digits, a hyphen, and four digits” can be represented by a regex such as \d{3}-\d{4}. The validation succeeds only when the complete string matches the expected pattern.

Phone-number formats vary by country and application. A regex that is correct for one local format may reject valid numbers from another region. For that reason, first define exactly which formats your application accepts.

How String.matches() Validates a Phone Number

The String.matches() method takes a regular expression and returns true when the entire string matches that expression. Otherwise, it returns false.

</>
Copy
boolean valid = phoneNumber.matches(regex);

Common regex elements used in the examples below include:

  • \d matches a digit according to Java’s regex rules.
  • {3} means exactly three occurrences of the preceding pattern.
  • {10} means exactly ten occurrences.
  • A hyphen written directly in these patterns matches a literal hyphen.

Inside Java source code, the regex backslash must itself be escaped. Therefore, regex \d{3}-\d{4} is written as the Java string literal "\\d{3}-\\d{4}".

Validate Phone Number Format NNN-NNNN

In this example, we will get a phone number in a string. Then we shall define a regular expression, that matches the phone numbers only with a correct format.

We use String.matches() method and pass regular expression as argument. String.matches() returns the boolean value true if this string matches with the regular expression, else it returns false.

Example.java

</>
Copy
public class Example {
	public static void main(String[] args) {
		isValidPhoneNumber("754-3010");
		isValidPhoneNumber("75 3010");
	}
	
	/**
	 * Method to validate phone number of format NNN-NNNN, example 754-3010
	 * @param phone_number
	 * @return true if phone_number is valid, false if not
	 */
	public static boolean isValidPhoneNumber(String phone_number) {
		boolean isValid =  phone_number.matches("\\d{3}-\\d{4}");
		System.out.println(phone_number+" : "+isValid);
		return isValid;
	}
}

The regular expression "\\d{3}-\\d{4}" requires three digits, followed by one hyphen, followed by four digits. Because matches() tests the complete string, extra characters before or after this format also cause the validation to fail.

Therefore, "754-3010" produces true, while "75 3010" produces false because it does not contain the required three-digit group, hyphen, and four-digit group.

Output

754-3010 : true
75 3010 : false

Validate Phone Number Format NNN-NNN-NNN-NNNN

In this example, we shall learn to validate phone numbers of format: three digits, hyphen, three digits, hyphen, three digits, hyphen, four digits.

Example.java

</>
Copy
/**
 * Java Example Program to validate phone number
 */
public class Example {

	public static void main(String[] args) {
		isValidPhoneNumber("001-541-754-3010");
		isValidPhoneNumber("755-253-3010");
	}
	
	/**
	 * Method to validate phone number of format NNN-NNN-NNN-NNNN, example 001-541-754-3010
	 * @param phone_number
	 * @return true if phone_number is valid, false if not
	 */
	public static boolean isValidPhoneNumber(String phone_number) {
		boolean isValid =  phone_number.matches("\\d{3}-\\d{3}-\\d{3}-\\d{4}");
		System.out.println(phone_number+" : "+isValid);
		return isValid;
	}
}

The pattern in this example checks only the specified digit-and-hyphen structure. It does not determine whether the groups represent a real country code, area code, carrier, or assigned telephone number.

Output

001-541-754-3010 : true
755-253-3010 : false

Validate a Phone Number Containing Exactly 10 Digits

When your application’s requirement is simply an uninterrupted sequence of exactly ten digits, you can use the pattern \d{10}.

This is a format check only. A ten-digit match does not by itself prove that the number is a valid or active mobile number in India or any other country.

Example.java

</>
Copy
/**
 * Java Example Program to validate phone number
 */
public class Example {

	public static void main(String[] args) {
		isValidPhoneNumber("9876543210");
		isValidPhoneNumber("7533010");
	}
	
	/**
	 * Method to validate phone number of format NNNNNNNNNN, example 9876543210
	 * @param phone_number
	 * @return true if phone_number is valid, false if not
	 */
	public static boolean isValidPhoneNumber(String phone_number) {
		boolean isValid =  phone_number.matches("\\d{10}");
		System.out.println(phone_number+" : "+isValid);
		return isValid;
	}
}

Output

9876543210 : true
7533010 : false

The first value contains exactly ten digits, so it matches. The second contains only seven digits, so matches() returns false.

Validate Phone Numbers with Optional Spaces or Hyphens

Some applications accept more than one presentation format. For example, you may want to accept 9876543210, 98765 43210, and 98765-43210. A regex can make the separator optional when those are the exact formats you intend to support.

</>
Copy
public class Example {
    public static void main(String[] args) {
        System.out.println(isValidPhoneNumber("9876543210"));
        System.out.println(isValidPhoneNumber("98765 43210"));
        System.out.println(isValidPhoneNumber("98765-43210"));
        System.out.println(isValidPhoneNumber("9876-543210"));
    }

    public static boolean isValidPhoneNumber(String phoneNumber) {
        return phoneNumber != null
                && phoneNumber.matches("\\d{5}[ -]?\\d{5}");
    }
}

Output

true
true
true
false

In [ -]?, the character class permits either a space or a hyphen, and ? makes that separator optional. The two digit groups are still required to contain exactly five digits each.

Handle null Phone Numbers Before Calling matches()

Calling matches() on a null reference causes a NullPointerException. If the phone number may be missing, check for null before applying the regex.

</>
Copy
boolean isValid = phoneNumber != null
        && phoneNumber.matches("\\d{10}");

You can also decide separately whether an empty string should be considered missing input or invalid input. The regex \d{10} does not match an empty string.

Phone Number Regex Validation Checks Format, Not Whether the Number Exists

A regular expression answers a structural question: does this text have the shape you specified? It cannot by itself determine whether a telephone number has been assigned, is currently reachable, or belongs to a particular person.

It is therefore useful to distinguish several different requirements:

  • Format validation: Does the input contain the expected number of digits and separators?
  • Numbering-plan validation: Is the number plausible under the numbering rules for a particular region?
  • Ownership or reachability verification: Can the user actually receive a call or verification message at that number?

The regex examples on this page address the first requirement.

Use libphonenumber for International Phone Number Validation

Regex is practical when your application accepts one small, precisely defined format. International phone numbers are more complicated because numbering rules, country calling codes, national prefixes, and valid lengths differ by region.

For applications that need region-aware parsing and validation, Google’s libphonenumber library is a more suitable approach than attempting to maintain one large regular expression. The project provides Java APIs for parsing, formatting, and checking phone numbers against supported numbering metadata.

Even library-based validation should be interpreted correctly: determining that a number is possible or valid according to numbering metadata is different from proving that the number is currently assigned or reachable.

Choosing Between Java Regex and libphonenumber

Validation requirementSuitable approach
Exactly 10 digitsString.matches() with \d{10}
One fixed local format such as NNN-NNNNA small regular expression
A few explicitly permitted separatorsA carefully defined regular expression
Country-specific and international numbering rulesA phone-number library such as libphonenumber
Confirm that a user controls the numberA separate verification process, such as sending a verification code

Common Java Phone Number Validation Mistakes

  • Do not assume that a regex match proves a phone number exists.
  • Do not use one country’s fixed-length regex as a universal international phone-number validator.
  • Remember to escape regex backslashes inside Java string literals, such as "\\d{10}".
  • Check for null before calling an instance method such as matches().
  • Define whether spaces, hyphens, parentheses, and country prefixes are accepted before writing the regex.
  • Avoid silently removing arbitrary characters before validation unless normalization is an explicit part of your application’s input rules.

Java Phone Number Validation Summary

To sum up, in this Java Tutorial, we learned how to validate phone numbers in Java using regular expression. We have gone through only some of the patterns, but you can make the pattern of phone number using regular expression, which matches the format you would like to validate based on the country or some specific requirement.

For a fixed application-specific format, String.matches() and a small regex provide a direct solution. For international or country-aware validation, use numbering-plan data from a maintained phone-number library rather than treating a simple regex as proof that a number is valid.