-3

Good afternoon, I need to write a method that will validate the phone number . I need the number can only contain numbers (0-9) and these characters : "()" "-" "+" , but everything else is forbidden!

For example :

 +210-998-234-01234 -OK
  210-998-234-01234-OK
 +21099823401234-OK
 +210-998-234-01234 -OK
 +210-(998)-(234)-(01234) - OK

+210-99A-234-01234 - FALSE , +210-999-234-0""234 -FALSE , +210-999-234-02;4 - FALSE

If the number contains something unresolved it should throw exception. I wrote this method but for some reason it doesn't work right. Please explain where I made a mistake when using matches()

I will be grateful for your help!

public void validatePhoneNumber(String phoneNumber) {
        if (!phoneNumber.matches("[ˆ0-9()\\-+]")) {
            throw new IncorrectlyEnteredDataException("Phone number have unresolved characters");

        }

1 Answers1

0

This regex will work for your phone numbers:

"^\\+?\\d{3}(?:\\d{11}|(?:-\\d{3,}){3}|(?:-\\(\\d{3,}\\)){3})"

But if you want to match all kind of variations of phone numbers, then see this solution - where Java generates REGEX for valid phone numbers:

How to validate phone numbers using regex

Regex shown in test bench and context:

public class TestBench {

        private final static Pattern VALID_PHONE_NUMBER_PATTERN =
                Pattern.compile("^\\+?\\d{3}(?:\\d{11}|(?:-\\d{3,}){3}|(?:-\\(\\d{3,}\\)){3})");

        public static void main (String[] args) {
            List<String> inputNumbers = Arrays.asList(
                    "+210-998-234-01234",       // PASS
                    "210-998-234-01234",        // PASS
                    "+21099823401234",          // PASS
                    "+210-(998)-(234)-(01234)", // PASS
                    "+210-99A-234-01234",       // FAIL
                    "+210-999-234-0\"\"234",    // FAIL
                    "+210-999-234-02;4",        // FAIL
                    "-210+998-234-01234",       // FAIL
                    "+210-998)-(234-(01234"     // FAIL
            );

            for (String number : inputNumbers) {
                validatePhoneNumber(number);
            }
        }

    private static void validatePhoneNumber(String phoneNumber) {
        Matcher matcher = VALID_PHONE_NUMBER_PATTERN.matcher(phoneNumber);
        if(matcher.matches()) {
            System.out.println("This is a valid phone number: " + matcher.group());
        }
    }

}

Output:

This is a valid phone number: +210-998-234-01234
This is a valid phone number: 210-998-234-01234
This is a valid phone number: +21099823401234
This is a valid phone number: +210-(998)-(234)-(01234)

Comment:

Notice: You can change on how many numbers you can tolerate by changing X and Y in the regex and so on, see below for clarification:

"^\\+?\\d{3}(?:\\d{X}|(?:-\\d{Y,}){3}|(?:-\\(\\d{Y,}\\)){3})"

In the regex suggested, we asume that there will always be three digits first before another variation comes.

DigitShifter
  • 801
  • 5
  • 12