Hi Guy’s Welcome to Proto Coders Point. In this article let’s checkout a regular expression for phone number validation.
I want a regex that matches following phone number pattern string:-
- XXXXXXXXXX -> 10 digit mobile number validation.
- +91 XXXXXXXXXX -> Country code + 10 digit phone number.
- (XXX) XXX XXXX -> Phone number with brackets separator.
- (XXX) XXX-XXXX -> Number with brackets & dash separator.
- XXX-XXX-XXXX -> Phone Number with dash separator.
and much more.
Common Phone number group
- Group1: Country Code (e.g. 1 or 86).
- Group2: Area Code (e.g. 808).
- Group3: Exchange (e.g. 555).
- Group4: Subscriber Number (e.g.1234).
- Group5: Extension (e.g. 5678).
Regular Expression for phone number validation
International phone number regex
^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$
Explanation of above phone number regex
^\s* | Starting line , accept white space at beginning. |
(?:\+?(\d{1,3}))? | Match country code, here ‘?’ makes it optional. remove ‘?’ to validate phone number and make it mandatory. |
[-. (]* | Match special character like bracket which may appear between the country code & area code. |
(\d{3}) | Area code of 3 digit in phone number string. add ‘?’ at end to make area code optional. |
[-. )]* | Match special character like bracket which may appear between the country code & area code. |
(\d{3}) | Exchange Number of 3 digit in phone regex string. add ‘?’ at end to make area code optional. |
[-. ]* | Match special character like dash which may appear between. |
(\d{4}) | Subscriber number of 4 digit in phone number string. |
(?: *x(\d+))? | Optional Extensional Number. |
\s*$ | Accept any white space at ending of phone number string. |