Reputation: 49
I am pretty much entirely new to writing regex, but i have gotten a task where i must create a phone number validation system.
Currently it is a bit of a headache for me.
My current progress has led me to:
^([+]45|[(][+]45[)]?|[(]0045[)]|0045)?\s*([0-9]{8})$
There are two things i need to achieve:
Country code. The country code can be written in various formats.
The Phone number
The phone number is assumed to always be from my country (which is why the country code always
the same as well
The issue comes when 00 is used for the country code. While I want to require the phone number to be with 8 digits, when the country code is 0045, only 4 digits for the phone number are required to get a "true" result.
I just cannot figure out how to ensure that this will be the case. Can this even be done in a reasonable way?
Upvotes: 0
Views: 1896
Reputation: 163207
To match 8 digits for the phone number excluding the prefix, you can match either +45 or (45) or (0045) or 0045 followed by 8 digits.
Or match 8 digits asserting the number does not start with 00
for a country code using a negative lookahead (?!00)
^(?:\+45|\(\+45\)|\(0045\)|0045|(?!00))\d{8}$
Explanation
^
Start of string(?:
Non capture group
\+45|\(\+45\)|\(0045\)|0045|(?!00)
Match either of the alternations, or assert not 00
at the start of the string)
Close non capture group\d{8}
Match 8 digits$
End of stringUpvotes: 2
Reputation: 49
I have altered the expression to: ^(^([+]45|[(][+]45[)]?|[(]0045[)]|0045)?\s*([1-9]{1})([0-9]{7})$
Which works for my purpose
But better solutions might be required later as international numbers might also be accepted at a later point.
Upvotes: 0