Reputation: 33
I am new to RegEx I am trying to validate a phone number with 10 digit and +
and 2 digit country code as optional. Tried with few regex but I'm not able to make +
and the country code as optional ^[+]*\d[0-9]{10,12}$
. Can anyone tell me where I'm wrong. Thanks in advance.
Upvotes: 3
Views: 2977
Reputation: 8332
If I understand your question correctly (it's a bit fuzzy with the optional part), none of the given answers will do what you want. So here's my go at it ;)
^(?:\+\d\d)?\d{10}$
This starts with an optional non capturing group with the +
and the country code. Then followed by the 10 digits.
Upvotes: 3
Reputation: 1290
Are you using Html5 pattern? if yes, below could be your answer,
<input type="text" pattern="[\+][\(]\d{2}[\)]\d{10}" required/>
e.g. format: +(91)1234567890
Upvotes: -1
Reputation: 627100
You need to enclose the first two digits with an optional non-capturing group:
^[+]?(?:[0-9]{2})?[0-9]{10}$
^^^^^^^^^^^^^
See the regex demo.
Details:
^
- start of string[+]?
- an optional +
(?:[0-9]{2})?
- an optional sequence of 2 digits[0-9]{10}
- 10 digits$
- end of string.Upvotes: 3