DMP
DMP

Reputation: 543

Regex that validate for a number with length 8, 11, 13 followed by an optional + symbol

I have following regex

^\+?[0-9]*$

I want to validate for a number with length 8, 11, 13 followed by an optional + symbol but don't know how to add lengths 8,11,13 in it.

If + symbol is included the length of whole string must be 8,11 or 13

Upvotes: 0

Views: 1801

Answers (2)

The fourth bird
The fourth bird

Reputation: 163277

You regex matches an optional plus sign and a digit [0-9] repeated zero or more times using the asterix *. The regex could also match an empty string or +1

You could use a quantifier like {8}, {11} and {13}.

^(?:\+(?:[0-9]{12}|[0-9]{10}|[0-9]{7})|(?:[0-9]{13}|[0-9]{11}|[0-9]{8}))$

Match either a plus sign + followed by the digits with the quantifiers for {12}, {10} and {8}.

Or match the digits using a quantifier for {13}, {11} and {9}

Upvotes: 2

Leyff da
Leyff da

Reputation: 226

You could use double conditionnal :
^\+[0-9]{8}([0-9]{3}[0-9]{2}?)?$

Explanation :

^ Start of the string
\+ escaped + symbol
[0-9]{8} It will go for 8 digit,
([0-9]{3} then 3 more digits
[0-9]{2} then 2 more digits
?) which is optionnal
? the whole part after 8 digits is also optionnal
$ end of the string

Upvotes: 0

Related Questions