4.3. Validate International Phone Numbers
Problem
You want to validate international phone numbers. The numbers should start with a plus sign, followed by the country code and national number.
Solution
Regular expression
^\+(?:[0-9]●?){6,14}[0-9]$| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
JavaScript example
function validate(phone) {
var regex = /^\+(?:[0-9] ?){6,14}[0-9]$/;
if (regex.test(phone)) {
// Valid international phone number
} else {
// Invalid international phone number
}
}Follow Recipe 3.6 to implement this regular expression with other programming languages.
Discussion
The rules and conventions used to print international phone numbers vary significantly around the world, so it’s hard to provide meaningful validation for an international phone number unless you adopt a strict format. Fortunately, there is a simple, industry-standard notation specified by ITU-T E.123. This notation requires that international phone numbers include a leading plus sign (known as the international prefix symbol), and allows only spaces to separate groups of digits. Although the tilde character (~) can appear within a phone number to indicate the existence of an additional dial tone, it has been excluded from this regular expression since it is merely a procedural element (in other words, it is not actually dialed) and is infrequently used. Thanks to the international phone numbering plan (ITU-T E.164), phone numbers cannot contain more than 15 digits. The ...