-3

I am trying to validate a phone number using Java. How can I ensure that the string is also the correct length (10 digits).

do{
    System.out.println("Please provide the phone number starting with area code: ");
    this.phone = input.nextLine();
} while (!phone.matches("[0-9]"));
Paul
  • 4,160
  • 3
  • 30
  • 56
Chief
  • 3
  • 3

1 Answers1

0

you have to change your regular expression to match exactly 10 digits.

do{
    System.out.println("Please provide the phone number starting with area code: ");
    this.phone = input.nextLine();
}while (!phone.matches("[0-9]{10}"));

One thing: I'm not sure if this type of validation is good. What if the user enters his phone number with a leading plus sign or something like that? Whitespaces as seperator?

Joshua K
  • 2,407
  • 1
  • 10
  • 13