Validate phone number using RegEx and Java

Java example of how to validate a phone number in various formats using regular expressions.

Contextual Ads

More Java Resources


  1. public class Validate
  2. {
  3.  public static void main(String args[])
  4.  {
  5.                 ValidatePhoneNumber("1-555-555-5555");
  6.                 ValidatePhoneNumber("1.555-555-5555");
  7.                 ValidatePhoneNumber("555-555-5555");
  8.                 ValidatePhoneNumber("555 555-5555");
  9.                 ValidatePhoneNumber("1 555 5555");
  10.                 ValidatePhoneNumber("555-WinNow");
  11.                 ValidatePhoneNumber("1-555-555");
  12.                 ValidatePhoneNumber("555-5555");
  13.  }
  14.  public static boolean ValidatePhoneNumber(String phNumber)
  15.  {
  16.  String msgResult = "";
  17.  boolean valResult = false;
  18.  String numPattern = "(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}";
  19.                 valResult = phNumber.matches(numPattern);
  20.  if (valResult)
  21.  {
  22.                         msgResult = "The phone number validates.";
  23.  }
  24.  else
  25.  {
  26.                         msgResult = "The phone number does not validate";
  27.  }
  28.  System.out.println(msgResult);
  29.  return valResult;
  30.  }
  31. }
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top