United Kingdom Phone Numbers: Format, Area Code & Validation Guide
Learn UK phone number formats – from basic structure and area codes to validation with regular expressions. Essential for businesses operating in the UK, developers building telephony applications, and anyone communicating with UK contacts.
Learn UK phone number formats – from basic structure and area codes to validation with regular expressions. Essential for businesses operating in the UK, developers building telephony applications, and anyone communicating with UK contacts.
UK Phone Numbering System Overview
Ofcom (Office of Communications) manages the UK's phone numbering system. The system categorizes numbers into several key types:
Geographic Numbers: Tied to specific locations. Begin with 01 or 02.
Mobile Numbers: Used for mobile phones and wireless devices. Begin with 07.
Non-Geographic Numbers: Not linked to a location. Start with 03 (charged at standard geographic rates), 08 (special-rate services), and 09 (premium-rate services).
International Dialing Format
Call the UK from abroad using country code +44. When dialing internationally:
UK mobile: 07700 900123 → International: +44 7700 900123
The E.164 format is the international standard for phone numbers, limiting them to 15 digits including the country code. Store numbers in E.164 format (e.g., +442079460958) without spaces or formatting. Display formatting can include spaces for readability.
Number Portability
Ofcom regulations make UK phone numbers fully portable. As of April 3, 2023, the "One Touch Switch" process lets you:
Keep your phone number when switching providers (both geographic and mobile numbers)
Initiate the switch through the new provider only
Complete the porting process within one working day for mobile numbers
All UK communications providers are legally required to support number portability. Service providers cannot refuse a porting request, and customers retain the right to port their number at any time without penalty.
Geographic Numbers
Geographic numbers reflect the UK's regional structure. Area codes vary in length from 2 to 5 digits depending on population density and historical network development.
Area Code Structure
Area codes range from 2 to 5 digits (after the initial 0). Shorter area codes serve densely populated areas like major cities, allowing more individual phone numbers.
2-Digit Area Codes (Format: 02X): Major metropolitan areas. Example: 020 for London.
3-Digit Area Codes (Format: 01X1 or 011X): Large areas and cities. Examples: 0117 for Bristol, 0121 for Birmingham.
4-Digit Area Codes (Format: 01XXX): Smaller towns and rural areas. Example: 01946 for Whitehaven.
5-Digit Area Codes (Format: 01XXXX): Less common, found in specific areas due to historical reasons. Examples: 01335 for Ashbourne, 01773 for Belper. Often have shorter local numbers (5 or 6 digits).
Additional Examples by Category:
3-Digit Area Codes:
0113 - Leeds
0114 - Sheffield
0115 - Nottingham
0116 - Leicester
0131 - Edinburgh
0141 - Glasgow
0151 - Liverpool
0161 - Manchester
0191 - Tyne and Wear
4-Digit Area Codes:
01224 - Aberdeen
01382 - Dundee
01472 - Grimsby
01582 - Luton
01733 - Peterborough
01865 - Oxford
Major UK Cities Quick Reference:
City
Area Code
Format
Example
London
020
(020) xxxx xxxx
020 7946 0958
Birmingham
0121
(0121) xxx xxxx
0121 496 0123
Manchester
0161
(0161) xxx xxxx
0161 496 0345
Leeds
0113
(0113) xxx xxxx
0113 496 0678
Glasgow
0141
(0141) xxx xxxx
0141 496 0234
Liverpool
0151
(0151) xxx xxxx
0151 496 0456
Edinburgh
0131
(0131) xxx xxxx
0131 496 0789
Bristol
0117
(0117) xxx xxxx
0117 496 0321
Cardiff
029
(029) xxxx xxxx
029 2018 0123
Belfast
028
(028) xxxx xxxx
028 9018 0456
Geographic Number Format
The standard format for a geographic number is 0XXX XXX XXXX (where XXX represents the area code). Total length is usually 10 digits, or 9 digits in rare cases with 5-digit area codes.
For Display: Use spaces to group digits for readability:
Geographic: 020 7946 0958 or (020) 7946 0958
Mobile: 07700 900123
International: +44 20 7946 0958
For Storage/Processing: Use E.164 format without spaces:
+442079460958 (geographic)
+447700900123 (mobile)
This ensures consistency for validation, database storage, and API integration while maintaining user-friendly display formatting.
Mobile Numbers
UK mobile numbers always start with 07 and are 10 digits long. Specific ranges include:
070: Personal Numbering Services – virtual mobile numbers, follow-me services, and personal assistant services. Charged at a higher rate than standard mobile numbers.
071-075 & 077-079: Standard mobile phone services, mobile broadband, and machine-to-machine (M2M) communications. The 077-079 range represents newer allocations and includes legacy paging services and IoT device connectivity.
Mobile Number Examples:
07700 900123 (standard mobile)
07911 123456 (standard mobile)
07400 123456 (standard mobile)
07521 987654 (standard mobile)
MVNO Number Allocation
Mobile Virtual Network Operators (MVNOs) like Giffgaff and Tesco Mobile don't have dedicated number ranges. MVNOs lease network infrastructure from one of four UK Mobile Network Operators (MNOs):
EE (BT)
Virgin Media O2
Vodafone
Three
MVNO customers receive numbers from their host network's allocated ranges. Due to number portability, it is not possible to determine a current provider solely from the number prefix—only the original allocating network.
Non-Geographic Numbers
Non-geographic numbers offer businesses and organizations a national presence without being tied to a specific location.
03 Numbers
03 numbers are charged at the same rate as standard geographic calls and are included in mobile phone inclusive minutes. Widely used by:
Corporate contact centers
Government services
Healthcare providers
Educational institutions
Examples of 03 Numbers in Use:
0300 200 3300 - UK Government departments
0333 123 4567 - Many corporate helplines
0345 600 4999 - Various business services
0370 000 3000 - National organizations
08 Numbers
08 numbers are special-rate services with varying costs. Ofcom regulations legally require businesses to clearly disclose call charges. Categories include:
0800/0808 (Freephone): Free to call from landlines and mobiles (since July 2015).
0843/0844/0845 (Business Rate): Service charge up to 7p per minute, plus access charge (typically 8p-65p per minute depending on provider).
0870 (Business Rate): Service charge up to 13p per minute, plus access charge.
0871/0872/0873 (Higher Rate): Service charge up to 13p per minute, plus access charge. These are often used for premium support services, entertainment services, and information lines.
Cost Structure (effective July 2015):
All 08 numbers (except 0800/0808) use a two-part charging structure:
Service Charge: Set by the organization you're calling (must be disclosed)
Access Charge: Set by your phone provider (typically 8p-65p per minute from mobiles, up to 16p per minute from landlines)
Number Range
Service Charge
Typical Total Cost
Use Case
0800/0808
Free
Free
Customer service, helplines
0843/0844
Up to 7p/min
15p-72p/min
Business contact centers
0845
Up to 7p/min
15p-72p/min
Business services
0870
Up to 13p/min
21p-78p/min
Corporate helplines
0871/0872/0873
Up to 13p/min
21p-78p/min
Premium business services
Note: Costs from landlines are generally lower than from mobiles. Check with your provider for exact access charges.
09 Numbers
09 numbers are premium-rate services used for adult entertainment, competitions, and voting lines. These numbers carry the highest call charges – up to £3.60 per minute plus access charges – and may include a connection fee of 5p–£6 per call.
Regulatory Framework:
Ofcom regulates premium-rate services, which must comply with strict consumer protection rules:
Price Transparency: Service providers must clearly state all charges before connection
Service Charge Caps: 09 numbers are capped at £3.60 per minute plus access charge (source)
Age Verification: Required for adult services (typically 098x ranges)
Complaint Handling: Consumers can complain to Ofcom about misleading services
Advertising Standards: All premium-rate service advertising must clearly display costs
Consumer Protection:
Refunds may be available for unauthorized or misleading charges
Phone bills must itemize premium-rate calls separately
Network providers can block access to 09 numbers upon customer request
The Phone-paid Services Authority (formerly PhonepayPlus) handles enforcement and consumer complaints
Validating UK Phone Numbers with Regular Expressions
Validate UK phone numbers using these regular expression patterns based on Ofcom's guidelines:
JavaScript
// Geographic Numbers (including variations in length)const geoPattern = /^(?:(?:\+44\s?|0)(?:(?:[1-5]\d{8,9}|[1-5]\d{3}[-\s]?\d{3}[-\s]?\d{3,4})))$/;
// Mobile Numbersconst mobilePattern = /^(?:(?:\+44\s?|0)7(?:[1-5|7-9])\d{8})$/;
// Freephone and Special Rate (0800, 0808, 084x, 087x)const specialPattern = /^(?:(?:\+44\s?|0)8(?:0(?:0|8)|4[3-4]|7[0-3])\d{7})$/;
// Premium Rate (09)const premiumPattern = /^(?:(?:\+44\s?|0)9\d{8})$/;
// All UK Numbers (Combined)const allUkPattern = /^(?:(?:\+44\s?|0)(?:(?:[1-5]\d{8,9}|[1-5]\d{3}[-\s]?\d{3}[-\s]?\d{3,4})|7(?:[1-5|7-9])\d{8}|8(?:0(?:0|8)|4[3-4]|7[0-3])\d{7}|9\d{8}))$/;
^ and $: Match the beginning and end of the string, ensuring the entire string is a valid number.
(?: ... ): Non-capturing group.
\+44\s?|0: Matches either the international prefix "+44" with an optional space or the national trunk prefix "0".
\d{n}: Matches exactly n digits.
[1-5|7-9]: Matches a single digit within the specified range.
[-\s]?: Matches an optional hyphen or whitespace character, allowing different formatting styles.
Edge Cases and Error Handling
Common Validation Challenges:
Mixed formatting:+44 (0)20 7946 0958 - Contains both international code and trunk prefix
Solution: Strip the (0) when +44 is present
Wrong length numbers:020 794 095 - Too short
Solution: Validate total digit count (9-10 digits after trunk/country code)
Invalid prefixes:06xx numbers - Not allocated in UK plan
Solution: Explicitly validate against known UK prefix ranges
Crown Dependencies:01481 (Guernsey), 01534 (Jersey), 01624 (Isle of Man)
Note: These use UK +44 code but have different regulatory rules
Error Handling Example:
JavaScript
functionvalidateWithDetails(phoneNumber) {
const sanitized = phoneNumber.replace(/[^\d+]/g, '');
if (sanitized.length < 10) {
return { valid: false, error: 'Number too short' };
}
if (sanitized.length > 13 && sanitized.startsWith('+44')) {
return { valid: false, error: 'Number too long' };
}
// Check for invalid prefixesif (/^0[046]/.test(sanitized)) {
return { valid: false, error: 'Invalid UK number prefix' };
}
// Run full validationconst ukPattern = /^(?:(?:\+44\s?|0)(?:(?:[1-5]\d{8,9})|7(?:[1-5|7-9])\d{8}|8(?:0(?:0|8)|4[3-5]|7[0-3])\d{7}|9\d{8}))$/;
if (ukPattern.test(phoneNumber)) {
return { valid: true, sanitized };
}
return { valid: false, error: 'Invalid UK phone number format' };
}
Best Practices for Phone Number Validation
Sanitize Input: Remove all non-digit characters except the "+" sign before validation.
Informative Error Messages: Provide specific error messages to guide users toward correct input.
Consider User Experience: Allow various formatting styles (e.g., spaces, hyphens) in user input.
Regularly Update Regex: Keep regex patterns up-to-date with Ofcom's numbering plan changes.
Input Sanitization Examples
JavaScript:
JavaScript
functionsanitizePhoneInput(input) {
// Remove all non-digits except leading +let sanitized = input.trim();
// Preserve leading + and digits onlyif (sanitized.startsWith('+')) {
sanitized = '+' + sanitized.slice(1).replace(/\D/g, '');
} else {
sanitized = sanitized.replace(/\D/g, '');
}
// Remove redundant (0) in international format
sanitized = sanitized.replace(/\+44\s?\(0\)/, '+44');
return sanitized;
}
// Examplesconsole.log(sanitizePhoneInput('020 7946 0958')); // '02079460958'console.log(sanitizePhoneInput('+44 (0)20 7946 0958')); // '+442079460958'console.log(sanitizePhoneInput('(020) 7946-0958')); // '02079460958'
Python:
Python
defsanitize_phone_input(input_str):
"""Sanitize phone number input for validation."""
sanitized = input_str.strip()
# Preserve leading + and digits onlyif sanitized.startswith('+'):
sanitized = '+' + re.sub(r'\D', '', sanitized[1:])
else:
sanitized = re.sub(r'\D', '', sanitized)
# Remove redundant (0) in international format
sanitized = re.sub(r'\+44\s?\(0\)', '+44', sanitized)
return sanitized
Troubleshooting Common Validation Failures
Issue
Symptom
Solution
False negative on valid London number
020 7946 0958 fails validation
Ensure regex allows for 2-digit area codes with 8-digit local numbers
Mobile number rejected
07700900123 fails without spaces
Allow for both spaced and non-spaced formats in regex
International format rejected
+44 20 7946 0958 fails
Ensure regex handles both +44 and 0 prefix alternatives
5-digit area codes fail
015396 12345 rejected
Add support for 9-digit geographic numbers (rare cases)
Crown Dependencies rejected
01481 xxxxxx (Guernsey) fails
Document whether your system should support these special cases
Follow these guidelines and use the provided regular expressions to validate UK phone numbers and ensure accurate communication. Understanding UK phone number formats is essential for any developer or business interacting with UK customers.
Frequently asked questions
UK phone numbers vary in format depending on their type. Geographic numbers typically follow a 0XXX XXX XXXX structure, mobile numbers start with 07 and are 10 digits long, and non-geographic numbers have specific prefixes like 03, 08, and 09.
Regular expressions are the most robust way to validate UK phone numbers. The article provides specific regex patterns for geographic, mobile, special-rate, and premium-rate numbers, ensuring accurate validation.
Geographic numbers in the UK begin with 01 or 02 and are tied to a specific location. They can have area codes of 2, 3, 4, or 5 digits, resulting in a total length of usually 10 digits but sometimes 9 digits.
The 07 prefix signifies a UK mobile number. These numbers are 10 digits long and are used for standard mobile phones, mobile broadband, and machine-to-machine communications. Numbers starting with 070 denote Personal Numbering services, often charged at higher rates.
Non-geographic numbers in the UK aren't tied to a specific location and start with 03, 08, or 09. 03 numbers are charged at standard rates, 08 numbers are special-rate services, and 09 numbers are premium-rate services.
Different area codes in UK phone numbers reflect the regional structure and historical development of the telephone network. Shorter area codes, like London's 020, are used for densely populated areas, allowing for more individual numbers.
You should use a regular expression for UK phone number validation whenever you need to ensure the accuracy and proper format of a phone number, particularly in applications, databases, or forms where incorrect data can cause problems.
UK numbers starting with 08 are special-rate services, with varying costs. 0800 and 0808 are freephone, 0843 and 0844 are business rate, while 0871, 0872, and 0873 are higher rate. Businesses using these numbers must disclose call charges.
The area code for London is 020. This is a 2-digit area code, indicative of major metropolitan areas, which allows for a larger number of individual phone numbers within the city.
Yes, you can use spaces and hyphens in UK phone numbers for readability. The regular expressions provided in the article allow for various formatting styles using spaces, hyphens, and the '+' sign before the country code.
Ofcom (Office of Communications) manages the UK's phone numbering system. They oversee the allocation of numbers, set regulations for number usage, and ensure the system adapts to growing demand and technological advancements.
UK 03 numbers provide a non-geographic alternative charged at standard geographic rates, often included in mobile inclusive minutes. They are widely used by corporate contact centers, government services, healthcare providers, and educational institutions.
International UK phone numbers begin with the prefix +44 followed by the national number without the leading zero. For example, +44 20 7946 0958 would be the international format for a London number.
Learn UK phone number formats – from basic structure and area codes to validation with regular expressions. Essential for businesses operating in the UK, developers building telephony applications, and anyone communicating with UK contacts.
UK Phone Numbering System Overview
Ofcom (Office of Communications) manages the UK's phone numbering system. The system categorizes numbers into several key types:
01or02.07.03(charged at standard geographic rates),08(special-rate services), and09(premium-rate services).International Dialing Format
Call the UK from abroad using country code +44. When dialing internationally:
0from the UK number+44Examples:
020 7946 0958→ International:+44 20 7946 095807700 900123→ International:+44 7700 900123The E.164 format is the international standard for phone numbers, limiting them to 15 digits including the country code. Store numbers in E.164 format (e.g.,
+442079460958) without spaces or formatting. Display formatting can include spaces for readability.Number Portability
Ofcom regulations make UK phone numbers fully portable. As of April 3, 2023, the "One Touch Switch" process lets you:
All UK communications providers are legally required to support number portability. Service providers cannot refuse a porting request, and customers retain the right to port their number at any time without penalty.
Geographic Numbers
Geographic numbers reflect the UK's regional structure. Area codes vary in length from 2 to 5 digits depending on population density and historical network development.
Area Code Structure
Area codes range from 2 to 5 digits (after the initial
0). Shorter area codes serve densely populated areas like major cities, allowing more individual phone numbers.02X): Major metropolitan areas. Example:020for London.01X1or011X): Large areas and cities. Examples:0117for Bristol,0121for Birmingham.01XXX): Smaller towns and rural areas. Example:01946for Whitehaven.01XXXX): Less common, found in specific areas due to historical reasons. Examples:01335for Ashbourne,01773for Belper. Often have shorter local numbers (5 or 6 digits).Additional Examples by Category:
3-Digit Area Codes:
0113- Leeds0114- Sheffield0115- Nottingham0116- Leicester0131- Edinburgh0141- Glasgow0151- Liverpool0161- Manchester0191- Tyne and Wear4-Digit Area Codes:
01224- Aberdeen01382- Dundee01472- Grimsby01582- Luton01733- Peterborough01865- OxfordMajor UK Cities Quick Reference:
Geographic Number Format
The standard format for a geographic number is
0XXX XXX XXXX(whereXXXrepresents the area code). Total length is usually 10 digits, or 9 digits in rare cases with 5-digit area codes.Examples by Area Code Length:
020 7946 0958(London)0117 496 0321(Bristol),0131 496 0789(Edinburgh)01382 654321(Dundee),01865 123456(Oxford)015396 12345(Sedbergh),016977 1234(Brampton - note: 4-digit local number)Number Formatting: Display vs. Storage
For Display: Use spaces to group digits for readability:
020 7946 0958or(020) 7946 095807700 900123+44 20 7946 0958For Storage/Processing: Use E.164 format without spaces:
+442079460958(geographic)+447700900123(mobile)This ensures consistency for validation, database storage, and API integration while maintaining user-friendly display formatting.
Mobile Numbers
UK mobile numbers always start with
07and are 10 digits long. Specific ranges include:077-079range represents newer allocations and includes legacy paging services and IoT device connectivity.Mobile Number Examples:
07700 900123(standard mobile)07911 123456(standard mobile)07400 123456(standard mobile)07521 987654(standard mobile)MVNO Number Allocation
Mobile Virtual Network Operators (MVNOs) like Giffgaff and Tesco Mobile don't have dedicated number ranges. MVNOs lease network infrastructure from one of four UK Mobile Network Operators (MNOs):
MVNO customers receive numbers from their host network's allocated ranges. Due to number portability, it is not possible to determine a current provider solely from the number prefix—only the original allocating network.
Non-Geographic Numbers
Non-geographic numbers offer businesses and organizations a national presence without being tied to a specific location.
03 Numbers
03numbers are charged at the same rate as standard geographic calls and are included in mobile phone inclusive minutes. Widely used by:Examples of 03 Numbers in Use:
0300 200 3300- UK Government departments0333 123 4567- Many corporate helplines0345 600 4999- Various business services0370 000 3000- National organizations08 Numbers
08numbers are special-rate services with varying costs. Ofcom regulations legally require businesses to clearly disclose call charges. Categories include:Cost Structure (effective July 2015):
All 08 numbers (except 0800/0808) use a two-part charging structure:
Note: Costs from landlines are generally lower than from mobiles. Check with your provider for exact access charges.
09 Numbers
09numbers are premium-rate services used for adult entertainment, competitions, and voting lines. These numbers carry the highest call charges – up to £3.60 per minute plus access charges – and may include a connection fee of 5p–£6 per call.Regulatory Framework:
Ofcom regulates premium-rate services, which must comply with strict consumer protection rules:
Consumer Protection:
Validating UK Phone Numbers with Regular Expressions
Validate UK phone numbers using these regular expression patterns based on Ofcom's guidelines:
// Geographic Numbers (including variations in length) const geoPattern = /^(?:(?:\+44\s?|0)(?:(?:[1-5]\d{8,9}|[1-5]\d{3}[-\s]?\d{3}[-\s]?\d{3,4})))$/; // Mobile Numbers const mobilePattern = /^(?:(?:\+44\s?|0)7(?:[1-5|7-9])\d{8})$/; // Freephone and Special Rate (0800, 0808, 084x, 087x) const specialPattern = /^(?:(?:\+44\s?|0)8(?:0(?:0|8)|4[3-4]|7[0-3])\d{7})$/; // Premium Rate (09) const premiumPattern = /^(?:(?:\+44\s?|0)9\d{8})$/; // All UK Numbers (Combined) const allUkPattern = /^(?:(?:\+44\s?|0)(?:(?:[1-5]\d{8,9}|[1-5]\d{3}[-\s]?\d{3}[-\s]?\d{3,4})|7(?:[1-5|7-9])\d{8}|8(?:0(?:0|8)|4[3-4]|7[0-3])\d{7}|9\d{8}))$/;Practical Implementation Examples
JavaScript/Node.js:
function validateUKPhone(phoneNumber) { // Sanitize input first const sanitized = phoneNumber.replace(/[^\d+]/g, ''); // Combined UK pattern const ukPattern = /^(?:(?:\+44\s?|0)(?:(?:[1-5]\d{8,9}|[1-5]\d{3}[-\s]?\d{3}[-\s]?\d{3,4})|7(?:[1-5|7-9])\d{8}|8(?:0(?:0|8)|4[3-4]|7[0-3])\d{7}|9\d{8}))$/; if (ukPattern.test(phoneNumber)) { return { valid: true, sanitized }; } return { valid: false, error: 'Invalid UK phone number format' }; } // Usage console.log(validateUKPhone('020 7946 0958')); // { valid: true, sanitized: '02079460958' } console.log(validateUKPhone('+44 7700 900123')); // { valid: true, sanitized: '+447700900123' }Python:
import re def validate_uk_phone(phone_number): """Validate UK phone number and return sanitized E.164 format.""" # Remove non-digit characters except + sanitized = re.sub(r'[^\d+]', '', phone_number) # UK phone pattern uk_pattern = r'^(?:(?:\+44\s?|0)(?:(?:[1-5]\d{8,9}|[1-5]\d{3}[-\s]?\d{3}[-\s]?\d{3,4})|7(?:[1-5|7-9])\d{8}|8(?:0(?:0|8)|4[3-4]|7[0-3])\d{7}|9\d{8}))$' if re.match(uk_pattern, phone_number): # Convert to E.164 format if sanitized.startswith('0'): e164 = '+44' + sanitized[1:] elif not sanitized.startswith('+'): e164 = '+44' + sanitized else: e164 = sanitized return {'valid': True, 'e164': e164} return {'valid': False, 'error': 'Invalid UK phone number format'} # Usage print(validate_uk_phone('020 7946 0958')) # {'valid': True, 'e164': '+442079460958'} print(validate_uk_phone('07700 900123')) # {'valid': True, 'e164': '+447700900123'}Explanation of Regex Components
^and$: Match the beginning and end of the string, ensuring the entire string is a valid number.(?: ... ): Non-capturing group.\+44\s?|0: Matches either the international prefix "+44" with an optional space or the national trunk prefix "0".\d{n}: Matches exactly n digits.[1-5|7-9]: Matches a single digit within the specified range.[-\s]?: Matches an optional hyphen or whitespace character, allowing different formatting styles.Edge Cases and Error Handling
Common Validation Challenges:
Mixed formatting:
+44 (0)20 7946 0958- Contains both international code and trunk prefix(0)when+44is presentWrong length numbers:
020 794 095- Too shortInvalid prefixes:
06xxnumbers - Not allocated in UK planCrown Dependencies:
01481(Guernsey),01534(Jersey),01624(Isle of Man)Error Handling Example:
function validateWithDetails(phoneNumber) { const sanitized = phoneNumber.replace(/[^\d+]/g, ''); if (sanitized.length < 10) { return { valid: false, error: 'Number too short' }; } if (sanitized.length > 13 && sanitized.startsWith('+44')) { return { valid: false, error: 'Number too long' }; } // Check for invalid prefixes if (/^0[046]/.test(sanitized)) { return { valid: false, error: 'Invalid UK number prefix' }; } // Run full validation const ukPattern = /^(?:(?:\+44\s?|0)(?:(?:[1-5]\d{8,9})|7(?:[1-5|7-9])\d{8}|8(?:0(?:0|8)|4[3-5]|7[0-3])\d{7}|9\d{8}))$/; if (ukPattern.test(phoneNumber)) { return { valid: true, sanitized }; } return { valid: false, error: 'Invalid UK phone number format' }; }Best Practices for Phone Number Validation
Input Sanitization Examples
JavaScript:
function sanitizePhoneInput(input) { // Remove all non-digits except leading + let sanitized = input.trim(); // Preserve leading + and digits only if (sanitized.startsWith('+')) { sanitized = '+' + sanitized.slice(1).replace(/\D/g, ''); } else { sanitized = sanitized.replace(/\D/g, ''); } // Remove redundant (0) in international format sanitized = sanitized.replace(/\+44\s?\(0\)/, '+44'); return sanitized; } // Examples console.log(sanitizePhoneInput('020 7946 0958')); // '02079460958' console.log(sanitizePhoneInput('+44 (0)20 7946 0958')); // '+442079460958' console.log(sanitizePhoneInput('(020) 7946-0958')); // '02079460958'Python:
def sanitize_phone_input(input_str): """Sanitize phone number input for validation.""" sanitized = input_str.strip() # Preserve leading + and digits only if sanitized.startswith('+'): sanitized = '+' + re.sub(r'\D', '', sanitized[1:]) else: sanitized = re.sub(r'\D', '', sanitized) # Remove redundant (0) in international format sanitized = re.sub(r'\+44\s?\(0\)', '+44', sanitized) return sanitizedTroubleshooting Common Validation Failures
020 7946 0958fails validation07700900123fails without spaces+44 20 7946 0958fails+44and0prefix alternatives015396 12345rejected01481 xxxxxx(Guernsey) failsFollow these guidelines and use the provided regular expressions to validate UK phone numbers and ensure accurate communication. Understanding UK phone number formats is essential for any developer or business interacting with UK customers.