0

I want to validate these phone number formats:

517123123
+48517123123
+48 517 123 123

(48)517123123
(48)517 123 123

517-123-123
48 517-123-123
48/517-123-123

48 517 123 123

I wrote this regex: (\+?)+(((\(([0-9]+){2,2}\)))|(([0-9]+){2,2})?)+(\/?)+(\s?)+(([0-9]+){9,9}|([0-9]+){3,3}(\s|-){1,1}([0-9]+){3,3}(\s|-){1,1}([0-9]+){3,3})

The problem is that it's makes big numbers like 8978978979878978967 valid. Where is my mistake?

1
  • 1
    Instead of validating phone numbers, why not just remove all non-numeric characters? Commented Jan 27, 2013 at 18:42

3 Answers 3

2

Looking at just the end of the regex, I see something that you seem to be doing in multiple places;

([0-9]+){3,3}

The + says at least one repeat of [0-9], which makes 1111111111111 a perfectly valid match. You then limit it to exactly 3 of those matches, which can still be a very long number. If you want exactly 3 digits, remove the +.

Sign up to request clarification or add additional context in comments.

Comments

1

may be you lost anchors.... however, use my regex ^(\+?(\(\d{2}\)|(\d{2})|(\d{2}[/ ])))?((\d{3} \d{3} \d{3})|(\d{3}-\d{3}-\d{3})|(\d{9}))$

Comments

1

At the moment I can't see what your regex is doing, there is too much superfluous stuff in it.

  1. You have too many groups

  2. You want to repeat optional characters!?

    e.g.:

    • (\+?)+, you don't need a group around and you don't want to repeat that, so \+? is what you want here.

    • (\s?)+, do you want to say "0 or more whitespaces"? Then \s* is what you need.

  3. When you write e.g. {9,9}, then you can remove one digit, {9} is the same.

  4. You are nesting quantifiers, thats the place where you allow too many characters. You have multiple places, where you do ([0-9]+){9,9}, that means 1 or more digits and repeat that 9 times.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.