Dev Dev - 3 months ago 21
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("[\\-\\+]", "");
System.out.println(phone);
final Matcher matcher = pattern.matcher(phone);
System.out.println(matcher.matches());

Answer

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

Sample:

boolean isValid = phoneString.matches(regexPattern);

Find more examples

Here is the regex pattern as per your input string:

\+\d(-\d{3}){2}-\d{4}

Online demo


Better use Spring validation annotation for validation.

Example

Comments