Home Tutorial Java Core Java validate phone number using regular expression

 
 

Share on Google+Share on Google+
Java validate phone number using regular expression
Posted on: November 29, 2012 at 12:00 AM
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
Advertisement

Related Tags for Java validate phone number using regular expression:


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.

Posted on: November 29, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com