Java validate 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.

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

Ads