Monday, January 9, 2017

Java How to validate phone number

In this post, I will show you How to validate phone number using Regular expression.



Standard phone number has pattern : Force starting with 3 digits follow by a "-" and 7 digits at the end.
\\d{3}-\\d{7}
Example:

  • 012-1231231    - Correct
  • 0121212323     - Wrong, missing "-"
  • B12-1212121    - Wrong, only digits

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatePhoneNumber {
  public static void main(String[] argv) {

      String phoneNumber = "111-8889999";
      //String sPhoneNumber = "434-88899991";
      //String sPhoneNumber = "112-888999A";

      Pattern pattern = Pattern.compile("\\d{3}-\\d{7}");
      Matcher matcher = pattern.matcher(phoneNumber);

      if (matcher.matches()) {
       System.out.println("Phone Number Valid");
      }
      else
      {
       System.out.println("Phone Number must be in the form XXX-XXXXXXX");
      }
 }
}
Share:

0 comments:

Post a Comment

Total Pageviews