Dev Dev -4 years ago 155
Java Question

phone Number validation in java

I want to validate a phone number in such Way :-

The field should allow the user to enter characters and should auto-correct. So an entry of "+1-908-528-5656" would not create an error for the user, it would just change to "19085285656".

I also want to number range between 9 to 11.

I also tried with the below code but not concluded to the final solution:

final String PHONE_REGEX = "^\\+([0-9\\-]?){9,11}[0-9]$";
final Pattern pattern = Pattern.compile(PHONE_REGEX);
String phone = "+1-908-528-5656";
phone=phone.replaceAll("[\\-\\+]", "");
final Matcher matcher = pattern.matcher(phone);

Answer Source

You can use simple String.matches(regex) to test any string against a regex pattern instead of using Pattern and Matcher classes.


boolean isValid = phoneString.matches(regexPattern);

Find more examples

Here is the regex pattern as per your input string:


Online demo

Better use Spring validation annotation for validation.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download