How to Validate a US Phone Number

By bhagwatchouhan
How to Validate a US Phone Number

We often require to validate the US or any country phone numbers so that users won't enter the wrong number. We can also make sure that the number entered by users is in the desired format. To do so, we are writing a console based implementation of the same in this post.
The Scanner class can be used to read a line from the console as shown below:

System.out.println( "Enter the phone number:" );
Scanner scanner = new Scanner( System.in );
String phone = scanner.nextLine();

The above code waits for user input and reads a line from the console as soon as the user hits Enter after entering the phone number.

The simplest match could be XXX-XXX-XXXX where X is any digit. We can match the phone number entered by the user as shown below:

if( phone.matches( "\\d{3}[-]\\d{3}[-]\\d{4}" ) ) {
	System.out.println( "Congratulations !! You have entered correct number." );
}

The whole program is as shown below:

import java.util.Scanner;
public class PhoneValidator { public static void main( String [] args ) {
System.out.println( "Enter the phone number:" );
Scanner scanner = new Scanner( System.in ); String phone = scanner.nextLine();
if( phone.matches( "\\d{3}[-]\\d{3}[-]\\d{4}" ) ) { System.out.println( "Congratulations !! You have entered correct number." ); } } }

Share this blog:

Profile picture for user bhagwatchouhan
bhagwatchouhan