Regular expression pattern in Java always is the best method to validate an user’s phone number. Here i provide a regex pattern to determines if the phone number is in correct format, the pattern force starting with 3 digits follow by a “-” and 7 digits at the end.


\\d = only digit allow
{3} = length

All phone numbers must in “xxx-xxxxxxx” format. For example
1) 012-6677889 – Passed
2) 01216677889 – Failed , “-” missing
3) A12-6677889 – Failed , only digit allow
4) 012-66778899 – Failed, only 7 digits at the end

Full source code of phone number validation in Java

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePhoneNumber {
  public static void main(String[] argv) {
      String sPhoneNumber = "605-8889999";
      //String sPhoneNumber = "605-88899991";
      //String sPhoneNumber = "605-888999A";
      Pattern pattern = Pattern.compile("\\d{3}-\\d{7}");
      Matcher matcher = pattern.matcher(sPhoneNumber);
      if (matcher.matches()) {
    	  System.out.println("Phone Number Valid");
    	  System.out.println("Phone Number must be in the form XXX-XXXXXXX");
Tags :
Founder of and, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Related Posts

Popular Posts