Home Tutorial Java Core Java validate phone number using regular expression

 
 

Java validate phone number using regular expression
Posted on: November 29, 2012 at 12:00 AM
In this tutorial, you will learn how to validate the phone number using regular expression.

Java validate phone number using regular expression

In this tutorial, you will learn how to validate the phone number using regular expression. The user is allowed to enter a number in a specific range i.e., a number should only be in the range of 6-9 digits. It it exceeds the range or decrease the range, an error will get displayed.

Example:

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ValidatePhoneNumber {
  public static boolean validatePhone(String phone){
                return phone.matches("^[0-9]{6,9}$");
        }
    public static void main(String[] argv) {
 	  Scanner input = new Scanner(System.in);
	  System.out.print("Enter Phone Number: ");
                String phone = input.nextLine();
                while(validatePhone(phone) != true) {
                        System.out.print("Invalid PhoneNumber!");
                        System.out.println();
                        System.out.print("Enter Phone Number: ");
                        phone = input.nextLine();
                }
        }
}

Output:

Enter Phone Number: 9999999999
Invalid PhoneNumber!
Enter Phone Number: 999999999

Related Tags for Java validate phone number using regular expression:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.