-4

I need a phone validator with the following conditions:

  • Optionally "+" at the start
  • 0 or 1 hyphens
  • At least 10 numbers

In Use the following regex: ^\+?(\d+)(-(\d+)|( \d+)+)?$

It works but it counts "+" and "-" too.

I can write for ex +123-45678

10 chars but only 8 numbers.

There should always be at least 10 numbers

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
Ivaapr
  • 1
  • 3

1 Answers1

1

Let's take this one part at a time:

  • Optionally "+" at the start

You've achieved this already, with:

^\+?
  • 0 or 1 hyphens

You can achieve this with a lookahead:

^(?=[^-]*-?[^-]*$)
  • At least 10 numbers

I presume that it should also contain ONLY numbers (and maybe a hyphen)? Again, using a lookahead:

^(?=(\d-?){10})

Putting it all together:

^\+?(?=[^-]*-?[^-]*$)(?=(\d-?){10})

This regex would be a lot simpler if the validation rules were less vague. It really depends on what your intended use is.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
  • What's your point? Your example was supposed to match, and it matches? – Tom Lord May 13 '16 at 14:31
  • Ok see [v2](https://regex101.com/r/qK1uM0/2). it matches but it's not supposed to match – Thomas Ayoub May 13 '16 at 14:32
  • Ahh yeah, fine. OP didn't actually specify that the phone numbers could contain ONLY digits - although that seems sensible. I'll provide the "Improved" variation too. – Tom Lord May 13 '16 at 14:34
  • and no letters :-| – Ivaapr May 13 '16 at 14:34
  • Done. All I needed was to change `(\d.*)` to `(\d-?)` – Tom Lord May 13 '16 at 14:38
  • Don't you think that is overly complex for a relatively easy requirement to just check a digit count? It can be done with just 1 lookahead. – Wiktor Stribiżew May 13 '16 at 14:43
  • @WiktorStribiżew I suppose you could simplify it slightly to: `^\+?(?=[^-]*-?[^-]*$)[\d-]{10,}$`, but the improvement isn't massive :/ – Tom Lord May 13 '16 at 14:56
  • Yes, but `(?=[^-]*-?[^-]*$)` prevents such a string from matching :) https://regex101.com/r/qK1uM0/4 – Tom Lord May 13 '16 at 15:03
  • ^\+?(?=[^-]*-?[^-]*$)(?=(\d-?){10}) well done! But it works med hyphen at the end – Ivaapr May 13 '16 at 15:10
  • @Ivaapr At a certain point, when the pattern matching gets too crazy, it's probably worth considering *not* doing this in one big regex ;) However, you could achieve this by simply changing the pattern to: `^\+?(?=[^-]*-?[^-]+$)(?=(\d-?){10})` (I just replaced a `*` with `+`). – Tom Lord May 13 '16 at 15:14