Share on Google+Share on Google+

Java validate phone number using regular expression

Advertisement
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

Advertisements

Advertisement

Posted on: November 29, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.