Phone number validation is an important process for any business or organization that needs to ensure that the phone numbers they are collecting are valid. A regular expression (regex) can be used to validate the length and numeric values of a phone number. This article will provide an overview of the regex used for phone number validation and provide examples of how it can be used.
This question already has an answer here:
Regular expression for validating US phone numbers 8 answers
The following regex should validate phone numbers of length 10 and only contain numeric values:
^\d{10}$
Try the regular expression
^\\d{10,15}$
Here \d
is a predefined character class for digits{10, 15}
quantifier stands for a repeat of 10 to 15 times of the previous pattern
Ex:
String input = "1234567890";
Pattern pattern = Pattern.compile("^\\d{10,15}$");
if (pattern.matcher(input).find()) {
System.out.println("Valid");
}