Western Sahara Phone Numbers: Format, Area Code & Validation Guide
Comprehensive guide to Western Sahara phone number system including +212 country code, E.164 formatting, and validation implementation for developers and telecom professionals.
This comprehensive guide explains Western Sahara's phone number system, including the +212 country code, E.164 formatting, and validation implementation for telecom professionals, developers, and system integrators. Learn how to validate Western Sahara phone numbers, implement international dialing, and comply with Morocco's telecommunications regulations for seamless integration in your applications.
Important Context: Western Sahara is a disputed territory with complex political status. Since 1975, Morocco has administered approximately 80% of the territory and integrated it into its telecommunications infrastructure under the Agence Nationale de Réglementation des Télécommunications (ANRT). Western Sahara operates within Morocco's regulatory and numbering framework. International recognition varies—the United States recognized Moroccan sovereignty in 2020, France in 2024, and the UK in 2025—but the territory remains contested. For telecommunications purposes, Western Sahara uses Morocco's country code (+212) and regulatory system.
Data Protection & Privacy: When handling Western Sahara phone numbers, comply with Morocco's Law No. 09-08 (February 18, 2009) on personal data protection, enforced by the Commission Nationale de Protection des Données Personnelles (CNDP). Phone numbers are classified as personal data under this law. Key requirements include:
Prior declaration or authorization: Processing phone numbers requires filing with the CNDP (declaration for standard processing; authorization if combined with national ID numbers or used for purposes beyond original collection)
Consent: Generally required before processing personal data, though narrowly interpreted exceptions exist
Security obligations: Implement technical and organizational measures to prevent unauthorized access, damage, or alteration
International transfers: Require CNDP authorization and recipient country must provide adequate protection or data subject consent
Penalties: Non-compliance carries fines from DH10,000 to DH600,000 and/or imprisonment (3 months to 4 years)
Morocco's data protection law predates GDPR but shares similar principles. If your operations are also subject to GDPR (e.g., EU-based customers), apply the stricter requirements. Phone data storage and processing must comply with both frameworks where applicable.
Understanding the Telecommunications Landscape in Western Sahara
The Agence Nationale de Réglementation des Télécommunications (ANRT) oversees Western Sahara's telecommunications infrastructure under Morocco's regulatory framework. Western Sahara's numbering plan aligns with Morocco's national system, affecting number formatting, validation, and regulatory compliance.
Morocco's control over Western Sahara telecommunications stems from its administration of the territory since 1975. For businesses, this means:
Regulatory compliance: All telecommunications operations must comply with ANRT regulations and Moroccan telecommunications law (Law 24-96 as amended)
Licensing: Operators require ANRT licenses; three main operators serve the region (Maroc Telecom, Orange Maroc, Inwi)
Infrastructure: Networks are fully integrated with Morocco's national infrastructure, including fiber optic connections extending into Mauritania
Recent developments: ANRT Decision DG/05/2025 (March 2025) mandates fiber optic network sharing among operators to increase competition
As of 2025, there is no alternative telecommunications infrastructure operating independently in Western Sahara. All services operate under Morocco's unified system.
As highlighted in sahara-developpement.com, significant investments have been made in the region's telecommunications infrastructure since 1975, focusing on expanding and modernizing networks. According to the U.S. International Trade Administration (July 2025), Morocco's telecom market was valued at $3.64 billion in 2024, with ongoing infrastructure improvements including Starlink negotiations initiated in 2024.
Western Sahara Country Code & Numbering Plan Structure
Western Sahara uses the +212 country code (Morocco) with a geographically based numbering system. Understanding regional number assignments ensures accurate routing and validation.
Morocco uses a closed 10-digit numbering plan in the format CC + N(S)N, where CC (Country Code) = 212, and N(S)N consists of 9 digits (ZABPQMCDU). The ANRT updates this plan as needed to accommodate growth—most recently documented in ITU Communication T02020000900030 (June 2025).
Consider geographic prefixes when validating local numbers to ensure correct regional routing. For comprehensive prefix assignments across Morocco (including Western Sahara), consult the ANRT's official operator number ranges (updated January 2024).
Emergency and Special Service Numbers
Western Sahara uses dedicated short codes for emergency and support services. Prioritize these calls in your systems and ensure accessibility.
Emergency Services
Police (19): Local law enforcement
Royal Gendarmerie (177): Rural and highway patrol
Ambulance/Fire (15): Medical and fire emergencies
Technical Requirements for Emergency Calls:
Must be reachable without SIM card, account balance, or network registration
Require priority routing over regular calls in network congestion
Should include location information transmission where technically feasible
Must attempt connection even with minimal signal strength
Legal Liability: Under Morocco's telecommunications law, operators face significant penalties for emergency call handling failures. Test emergency number accessibility rigorously and maintain fallback mechanisms. Document all emergency call routing logic for regulatory audits.
Support Services
Directory Enquiries (160): Number lookup assistance (hours and language support vary by operator)
Customer Service (114): General telecommunications support (hours and language support vary by operator)
Mobile Operator Prefixes
Three mobile operators serve Western Sahara with designated number ranges. Use prefixes to identify the operator for a given mobile number.
Operator Assignments
Operator
Prefix Ranges
Market Segment
Maroc Telecom
06-0x to 06-4x, 06-8x (excluding 06-83 to 06-86)
Consumer and Enterprise
Orange Maroc
06-5x, 06-6x, 07-0x, 07-2x, 07-5x, 07-8x
Consumer and Business
Inwi
06-7x, 06-9x, 07-1x, 07-6x, 07-7x
General Market
Mobile numbers follow the format [Operator Prefix][Subscriber Number] (e.g., 06-XXXXXXXX or 07-XXXXXXXX). Some prefixes like 06-8x are shared between operators and require nuanced validation.
Mobile Number Portability (MNP): Morocco implemented mobile number portability in 2007, allowing subscribers to keep their phone numbers when switching operators. Key facts:
Portability process: Reduced to 1 day as of April 2024 (previously 2 days)
RIO codes: Since November 2021, porting uses a 12-character alphanumeric RIO (Relevé d'Identité Opérateur) code
Centralized database: Managed via BDCPN (Centralized Number Portability Database) since December 2019
Implication: Prefix-based operator identification may be inaccurate for ported numbers; use HLR lookups for definitive operator identification
No information is available about MVNOs (Mobile Virtual Network Operators) currently operating in Western Sahara under distinct prefixes.
How to Validate Western Sahara Phone Numbers: Developer Implementation Guide
Implement Western Sahara phone number handling using validation, international formatting, and best practices.
Recommended Tools: For production implementations, use established libraries rather than custom regex:
Carrier metadata: libphonenumber includes operator assignments and format validation
MNP consideration: Libraries validate format but cannot determine current operator for ported numbers
1. Phone Number Validation Regex Patterns
Use regular expressions to validate number formats based on prefixes and lengths.
JavaScript
// Example validation regex for Western Sahara mobile numbersconst mobileRegex = /^(?:06|07)[0-9]{8}$/;
// More comprehensive regex incorporating operator-specific prefixesconst detailedMobileRegex = /^(?:06(?:[0-4]\d|5\d|6\d|7\d|8[0-247-9]|9\d)|07(?:0\d|1\d|2[0-4]\d|5[01]\d|6\d|7\d|8[0-3]\d))\d{6}$/;
// Test the regexconsole.log(detailedMobileRegex.test('0612345678')); // trueconsole.log(detailedMobileRegex.test('0761234567')); // trueconsole.log(detailedMobileRegex.test('0683123456')); // false (06-83 to 06-86 are not allocated for mobile)console.log(detailedMobileRegex.test('0791234567')); // false (07-9x is not allocated for mobile)
Python Example:
Python
import re
mobile_regex = re.compile(r'^(?:06|07)[0-9]{8}$')
detailed_mobile_regex = re.compile(r'^(?:06(?:[0-4]\d|5\d|6\d|7\d|8[0-247-9]|9\d)|07(?:0\d|1\d|2[0-4]\d|5[01]\d|6\d|7\d|8[0-3]\d))\d{6}$')
# Testprint(detailed_mobile_regex.match('0612345678')) # Match objectprint(detailed_mobile_regex.match('0791234567')) # None
Test regular expressions with valid and invalid inputs, including edge cases and formatting variations.
2. Converting to International E.164 Format
Convert local numbers to international format for international calls and SMS messaging using the ITU E.164 standard (maximum 15 digits: country code + subscriber number).
E.164 Format for Morocco/Western Sahara:
Format: +212 + 9-digit subscriber number (without leading 0)
Example: Local 0612345678 becomes +212612345678
Maximum length: 12 digits total (3-digit country code + 9-digit subscriber number)
JavaScript
// Convert local to international formatfunctiontoInternational(localNumber) {
// Remove formatting charactersconst cleaned = localNumber.replace(/[\s\-\(\)\.]/g, '');
// Handle different input formatsif (cleaned.startsWith('+212')) {
return cleaned; // Already in international format
}
if (cleaned.startsWith('00212')) {
return'+' + cleaned.substring(2); // Convert 00212 to +212
}
if (cleaned.startsWith('0') && cleaned.length === 10) {
return'+212' + cleaned.substring(1); // Remove leading 0, add +212
}
thrownewError('Invalid phone number format');
}
// Example usageconsole.log(toInternational('0612345678')); // +212612345678console.log(toInternational('+212612345678')); // +212612345678console.log(toInternational('00212612345678')); // +212612345678// Reverse: international to localfunctiontoLocal(internationalNumber) {
const cleaned = internationalNumber.replace(/[\s\-\(\)\.]/g, '');
if (cleaned.startsWith('+212')) {
return'0' + cleaned.substring(4);
}
if (cleaned.startsWith('00212')) {
return'0' + cleaned.substring(5);
}
if (cleaned.startsWith('0') && cleaned.length === 10) {
return cleaned; // Already local
}
thrownewError('Invalid international format');
}
console.log(toLocal('+212612345678')); // 0612345678
This standardized format ensures compatibility with international telecommunications systems and SMS gateways.
3. Number Preprocessing
Preprocess input before validation to handle formatting variations.
JavaScript
functionpreprocessNumber(number) {
// Type checkingif (number === null || number === undefined) {
thrownewError('Phone number cannot be null or undefined');
}
// Convert to string if neededconst str = String(number).trim();
if (str.length === 0) {
thrownewError('Phone number cannot be empty');
}
return str
.replace(/[\s\-\(\)\.]/g, '') // Remove whitespace, hyphens, parentheses, and periods
.replace(/^(\+212|00212)/, '0') // Normalize to local format with leading 0
.replace(/^212/, '0'); // Handle edge case of 212 without prefix
}
// Example usageconsole.log(preprocessNumber('+212 612 345 678')); // 0612345678console.log(preprocessNumber('0612-345-678')); // 0612345678console.log(preprocessNumber(' 00212 612 345 678 ')); // 0612345678
This function removes formatting characters and leading prefixes for pattern validation.
4. Comprehensive Validation Function
Combine preprocessing and regex validation into a single function for streamlined validation.
Toll-free (080x xxxxxxx): Free for callers; business pays for incoming calls. Format: +212-80-xxxxxxx. Used for customer service, government helplines, public information.
Premium rate (089x xxxxxxx): Higher cost charged to caller; portion goes to service provider. Format: +212-89-xxxxxxx. Used for professional consulting, information services, entertainment. Costs vary by service—check operator rate cards.
5. Error Handling and User Feedback
Provide clear error messages in multiple languages to guide users.
JavaScript
const errorMessages = {
en: {
invalidFormat: 'Invalid phone number format. Expected 10 digits starting with 05, 06, or 07.',
invalidPrefix: 'Invalid operator prefix. Check the first 3 digits.',
tooShort: 'Phone number is too short. Enter 10 digits.',
tooLong: 'Phone number is too long. Enter 10 digits.',
invalidLandline: 'Invalid landline number. Western Sahara landlines start with 5288 or 5289.',
invalidMobile: 'Invalid mobile number. Check the operator prefix.',
invalidTollFree: 'Invalid toll-free number. Format should be 080xxxxxxx.',
invalidPremium: 'Invalid premium rate number. Format should be 089xxxxxxx.',
nullOrEmpty: 'Phone number is required.',
invalidCharacters: 'Phone number contains invalid characters.'
},
fr: {
invalidFormat: 'Format de numéro de téléphone invalide. 10 chiffres attendus commençant par 05, 06 ou 07.',
invalidPrefix: 'Préfixe opérateur invalide. Vérifiez les 3 premiers chiffres.',
tooShort: 'Le numéro de téléphone est trop court. Saisissez 10 chiffres.',
tooLong: 'Le numéro de téléphone est trop long. Saisissez 10 chiffres.',
invalidLandline: 'Numéro fixe invalide. Les lignes fixes du Sahara Occidental commencent par 5288 ou 5289.',
invalidMobile: 'Numéro mobile invalide. Vérifiez le préfixe opérateur.',
invalidTollFree: 'Numéro gratuit invalide. Le format doit être 080xxxxxxx.',
invalidPremium: 'Numéro surtaxé invalide. Le format doit être 089xxxxxxx.',
nullOrEmpty: 'Le numéro de téléphone est requis.',
invalidCharacters: 'Le numéro de téléphone contient des caractères invalides.'
},
ar: {
invalidFormat: 'تنسيق رقم الهاتف غير صالح. يجب أن يتكون من 10 أرقام تبدأ بـ 05 أو 06 أو 07.',
invalidPrefix: 'بادئة المشغل غير صالحة. تحقق من الأرقام الثلاثة الأولى.',
tooShort: 'رقم الهاتف قصير جدًا. أدخل 10 أرقام.',
tooLong: 'رقم الهاتف طويل جدًا. أدخل 10 أرقام.',
nullOrEmpty: 'رقم الهاتف مطلوب.',
invalidCharacters: 'رقم الهاتف يحتوي على أحرف غير صالحة.'
}
};
functiongetErrorType(number, type) {
if (!number || number.trim().length === 0) return'nullOrEmpty';
try {
const cleaned = preprocessNumber(number).replace(/^0/, '');
if (cleaned.length < 9) return'tooShort';
if (cleaned.length > 9) return'tooLong';
if (type === 'landline' && !patterns.landline.test(cleaned)) return'invalidLandline';
if (type === 'mobile' && !patterns.mobile.test(cleaned)) return'invalidMobile';
if (type === 'tollFree' && !patterns.tollFree.test(cleaned)) return'invalidTollFree';
if (type === 'premiumRate' && !patterns.premiumRate.test(cleaned)) return'invalidPremium';
// Check prefix for general validationconst prefix = cleaned.substring(0, 2);
if (!['52', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '75', '76', '77', '78', '80', '89'].includes(prefix)) {
return'invalidPrefix';
}
return'invalidFormat';
} catch {
return'invalidCharacters';
}
}
functionvalidateAndProvideFeedback(number, type = 'any', language = 'en') {
const messages = errorMessages[language] || errorMessages.en;
if (!validateWesternSaharaNumber(number, type)) {
const errorType = getErrorType(number, type);
return {
valid: false,
error: messages[errorType] || messages.invalidFormat
};
}
const details = validateWithDetails(number, type);
return {
valid: true,
...details
};
}
// Example usageconsole.log(validateAndProvideFeedback('0612345678', 'mobile', 'en'));
// { valid: true, matchedType: 'mobile', formatted: {...} }console.log(validateAndProvideFeedback('0691234567', 'mobile', 'fr'));
// { valid: false, error: 'Numéro mobile invalide. Vérifiez le préfixe opérateur.' }console.log(validateAndProvideFeedback('123', 'any', 'ar'));
// { valid: false, error: 'رقم الهاتف قصير جدًا. أدخل 10 أرقام.' }
This approach enhances user experience by providing specific, actionable feedback on validation failures in the user's preferred language.
Edge cases: Null, empty string, whitespace only, extremely long input, international variants
Format variants: With/without spaces, hyphens, parentheses, country code variations (+212, 00212, 212)
Load testing: Validate performance under expected peak load
Regulatory Updates and Considerations
Monitor ANRT regulations for changes to the numbering plan, licensing requirements, and policies. Find updates on the ANRT Official Website.
Recent Updates (as of October 2025):
March 2025: ANRT Decision DG/05/2025 mandates fiber optic infrastructure sharing among operators
January 2025: Updated type approval requirements for telecommunications equipment (effective May 1, 2025), including new labeling and SAR (Specific Absorption Rate) display requirements
April 2024: Number portability timeframe reduced from 2 days to 1 day
June 2025: ITU Communication documenting Morocco's numbering plan updates
Licensing & Compliance Requirements:
Operator licensing: Telecommunications services for the public require ANRT licensing under Article 1 of Decision ANRT/DG/N°04-04 (April 6, 2004)
VoIP restrictions: Commercial VoIP services for the public restricted to licensed operators; violations punishable under Article 83 of Law 24-96
Data processing: Phone number collection/processing requires CNDP declaration or authorization (see Introduction section)
Equipment type approval: Terminal equipment requires ANRT type approval before market introduction
Compliance Checklist for Telecommunications Systems:
CNDP declaration/authorization filed for phone data processing
Consent mechanisms implemented for data collection
Data security measures documented and implemented
International transfer safeguards in place (if applicable)
Emergency number routing tested and prioritized
Validation handles current numbering plan (check ANRT updates quarterly)
Number portability considered in operator identification
Privacy policy updated to reference Law 09-08 requirements
Incident response plan for data breaches prepared
Regular security audits scheduled
As noted in afrol.com, Maroc Telecom's investment in a fiber optic line extending through Western Sahara into Mauritania signifies a growing emphasis on connectivity in the region (note: article date not verified; infrastructure details subject to change).
Conclusion
Follow these guidelines to implement and maintain telecommunications systems that integrate with Western Sahara's infrastructure and regulatory framework.
Key Takeaways:
Political & Regulatory Context: Western Sahara operates under Morocco's telecommunications framework (+212 country code, ANRT regulation)
Data Protection Mandatory: Law 09-08 requires CNDP filing, consent, security measures, and authorization for international transfers
Number Portability Active: Prefix-based operator identification unreliable since 2007 MNP implementation; reduced to 1-day process
Use Established Libraries: Leverage libphonenumber for production implementations rather than custom regex
Emergency Calls Critical: Technical and legal requirements for priority routing and accessibility testing
Security Essential: Implement SQL injection prevention, XSS protection, rate limiting, and data pseudonymization
Western Sahara phone numbers follow Morocco's national system due to the integration of their telecommunications infrastructure. They use a geographically based numbering system with specific prefixes for different regions like Laayoune (5288) and Dakhla (5289). Mobile numbers follow the format [Operator Prefix][Subscriber Number], such as 06-XXXXXXXX or 07-XXXXXXXX.
Use regular expressions to validate Western Sahara phone numbers based on prefixes and lengths provided by the ANRT. For example, a basic mobile number regex could be /^(?:06|07)[0-9]{8}$/. More complex regex can be used for specific operator prefixes for more accurate validation.
To convert a Western Sahara number to the international E.164 format, replace the leading '0' with '+212', the country code for Morocco. For instance, 0612345678 becomes +212612345678. This is crucial for international calls and SMS messages.
The area code for Laayoune, Western Sahara is 5288. This prefix is used for the metropolitan area and suburbs, primarily the main business district. Remember, Western Sahara's numbering plan is integrated with Morocco's system.
Western Sahara utilizes Morocco's country code (+212) because its telecommunications infrastructure operates under Morocco's regulatory framework, overseen by the ANRT. This integration means that while geographically distinct, Western Sahara's numbering plan aligns with Morocco's national system.
The Agence Nationale de R??glementation des T??l??communications (ANRT) regulates telecommunications in Western Sahara. Western Sahara's telecommunications operate under Morocco's regulatory framework, resulting in an aligned numbering plan.
Western Sahara uses the following emergency numbers: Police (19), Royal Gendarmerie (177), and Ambulance/Fire (15). These numbers must be accessible from any device regardless of SIM card presence or account balance.
Refer to the ANRT (Agence Nationale de R??glementation des T??l??communications) official website for detailed information on Western Sahara's number formatting and current regulatory updates. The ANRT oversees the region's telecommunications and provides the most up-to-date information.
Maroc Telecom, Orange Maroc, and Inwi are the primary mobile operators. Maroc Telecom uses prefixes like 06-0x to 06-4x and 06-8x (excluding 06-83 to 06-86); Orange Maroc uses 06-5x, 06-6x, 07-0x, etc.; and Inwi uses 06-7x, 06-9x, 07-1x, etc.
Preprocess phone numbers before validation to remove whitespace, hyphens, and other formatting characters. This ensures consistent validation against your defined patterns and improves the reliability of your validation process.
Accept various input formats and preprocess them to a standardized format before validation. This improves user experience by allowing for flexibility in how users enter phone numbers. Use clear and concise error messages to inform users about invalid formatting.
The ANRT Official Website (https://www.anrt.ma/en/infos-pratiques/ce-que-vous-devez-savoir/numerotation) provides the latest updates on Western Sahara's telecommunications regulations. It's important to stay informed about changes to the numbering plan and licensing requirements to ensure your systems remain compliant.
Introduction
This comprehensive guide explains Western Sahara's phone number system, including the +212 country code, E.164 formatting, and validation implementation for telecom professionals, developers, and system integrators. Learn how to validate Western Sahara phone numbers, implement international dialing, and comply with Morocco's telecommunications regulations for seamless integration in your applications.
Important Context: Western Sahara is a disputed territory with complex political status. Since 1975, Morocco has administered approximately 80% of the territory and integrated it into its telecommunications infrastructure under the Agence Nationale de Réglementation des Télécommunications (ANRT). Western Sahara operates within Morocco's regulatory and numbering framework. International recognition varies—the United States recognized Moroccan sovereignty in 2020, France in 2024, and the UK in 2025—but the territory remains contested. For telecommunications purposes, Western Sahara uses Morocco's country code (+212) and regulatory system.
Data Protection & Privacy: When handling Western Sahara phone numbers, comply with Morocco's Law No. 09-08 (February 18, 2009) on personal data protection, enforced by the Commission Nationale de Protection des Données Personnelles (CNDP). Phone numbers are classified as personal data under this law. Key requirements include:
Morocco's data protection law predates GDPR but shares similar principles. If your operations are also subject to GDPR (e.g., EU-based customers), apply the stricter requirements. Phone data storage and processing must comply with both frameworks where applicable.
Understanding the Telecommunications Landscape in Western Sahara
The Agence Nationale de Réglementation des Télécommunications (ANRT) oversees Western Sahara's telecommunications infrastructure under Morocco's regulatory framework. Western Sahara's numbering plan aligns with Morocco's national system, affecting number formatting, validation, and regulatory compliance.
Morocco's control over Western Sahara telecommunications stems from its administration of the territory since 1975. For businesses, this means:
As of 2025, there is no alternative telecommunications infrastructure operating independently in Western Sahara. All services operate under Morocco's unified system.
As highlighted in sahara-developpement.com, significant investments have been made in the region's telecommunications infrastructure since 1975, focusing on expanding and modernizing networks. According to the U.S. International Trade Administration (July 2025), Morocco's telecom market was valued at $3.64 billion in 2024, with ongoing infrastructure improvements including Starlink negotiations initiated in 2024.
Western Sahara Country Code & Numbering Plan Structure
Western Sahara uses the +212 country code (Morocco) with a geographically based numbering system. Understanding regional number assignments ensures accurate routing and validation.
Morocco uses a closed 10-digit numbering plan in the format CC + N(S)N, where CC (Country Code) = 212, and N(S)N consists of 9 digits (ZABPQMCDU). The ANRT updates this plan as needed to accommodate growth—most recently documented in ITU Communication T02020000900030 (June 2025).
Regional Prefixes and Coverage
Consider geographic prefixes when validating local numbers to ensure correct regional routing. For comprehensive prefix assignments across Morocco (including Western Sahara), consult the ANRT's official operator number ranges (updated January 2024).
Emergency and Special Service Numbers
Western Sahara uses dedicated short codes for emergency and support services. Prioritize these calls in your systems and ensure accessibility.
Emergency Services
Technical Requirements for Emergency Calls:
Legal Liability: Under Morocco's telecommunications law, operators face significant penalties for emergency call handling failures. Test emergency number accessibility rigorously and maintain fallback mechanisms. Document all emergency call routing logic for regulatory audits.
Support Services
Mobile Operator Prefixes
Three mobile operators serve Western Sahara with designated number ranges. Use prefixes to identify the operator for a given mobile number.
Operator Assignments
Mobile numbers follow the format
[Operator Prefix][Subscriber Number](e.g.,06-XXXXXXXXor07-XXXXXXXX). Some prefixes like 06-8x are shared between operators and require nuanced validation.Mobile Number Portability (MNP): Morocco implemented mobile number portability in 2007, allowing subscribers to keep their phone numbers when switching operators. Key facts:
No information is available about MVNOs (Mobile Virtual Network Operators) currently operating in Western Sahara under distinct prefixes.
How to Validate Western Sahara Phone Numbers: Developer Implementation Guide
Implement Western Sahara phone number handling using validation, international formatting, and best practices.
Recommended Tools: For production implementations, use established libraries rather than custom regex:
1. Phone Number Validation Regex Patterns
Use regular expressions to validate number formats based on prefixes and lengths.
// Example validation regex for Western Sahara mobile numbers const mobileRegex = /^(?:06|07)[0-9]{8}$/; // More comprehensive regex incorporating operator-specific prefixes const detailedMobileRegex = /^(?:06(?:[0-4]\d|5\d|6\d|7\d|8[0-247-9]|9\d)|07(?:0\d|1\d|2[0-4]\d|5[01]\d|6\d|7\d|8[0-3]\d))\d{6}$/; // Test the regex console.log(detailedMobileRegex.test('0612345678')); // true console.log(detailedMobileRegex.test('0761234567')); // true console.log(detailedMobileRegex.test('0683123456')); // false (06-83 to 06-86 are not allocated for mobile) console.log(detailedMobileRegex.test('0791234567')); // false (07-9x is not allocated for mobile)Python Example:
import re mobile_regex = re.compile(r'^(?:06|07)[0-9]{8}$') detailed_mobile_regex = re.compile(r'^(?:06(?:[0-4]\d|5\d|6\d|7\d|8[0-247-9]|9\d)|07(?:0\d|1\d|2[0-4]\d|5[01]\d|6\d|7\d|8[0-3]\d))\d{6}$') # Test print(detailed_mobile_regex.match('0612345678')) # Match object print(detailed_mobile_regex.match('0791234567')) # NoneTest regular expressions with valid and invalid inputs, including edge cases and formatting variations.
2. Converting to International E.164 Format
Convert local numbers to international format for international calls and SMS messaging using the ITU E.164 standard (maximum 15 digits: country code + subscriber number).
E.164 Format for Morocco/Western Sahara:
+212+ 9-digit subscriber number (without leading 0)0612345678becomes+212612345678// Convert local to international format function toInternational(localNumber) { // Remove formatting characters const cleaned = localNumber.replace(/[\s\-\(\)\.]/g, ''); // Handle different input formats if (cleaned.startsWith('+212')) { return cleaned; // Already in international format } if (cleaned.startsWith('00212')) { return '+' + cleaned.substring(2); // Convert 00212 to +212 } if (cleaned.startsWith('0') && cleaned.length === 10) { return '+212' + cleaned.substring(1); // Remove leading 0, add +212 } throw new Error('Invalid phone number format'); } // Example usage console.log(toInternational('0612345678')); // +212612345678 console.log(toInternational('+212612345678')); // +212612345678 console.log(toInternational('00212612345678')); // +212612345678 // Reverse: international to local function toLocal(internationalNumber) { const cleaned = internationalNumber.replace(/[\s\-\(\)\.]/g, ''); if (cleaned.startsWith('+212')) { return '0' + cleaned.substring(4); } if (cleaned.startsWith('00212')) { return '0' + cleaned.substring(5); } if (cleaned.startsWith('0') && cleaned.length === 10) { return cleaned; // Already local } throw new Error('Invalid international format'); } console.log(toLocal('+212612345678')); // 0612345678This standardized format ensures compatibility with international telecommunications systems and SMS gateways.
3. Number Preprocessing
Preprocess input before validation to handle formatting variations.
function preprocessNumber(number) { // Type checking if (number === null || number === undefined) { throw new Error('Phone number cannot be null or undefined'); } // Convert to string if needed const str = String(number).trim(); if (str.length === 0) { throw new Error('Phone number cannot be empty'); } return str .replace(/[\s\-\(\)\.]/g, '') // Remove whitespace, hyphens, parentheses, and periods .replace(/^(\+212|00212)/, '0') // Normalize to local format with leading 0 .replace(/^212/, '0'); // Handle edge case of 212 without prefix } // Example usage console.log(preprocessNumber('+212 612 345 678')); // 0612345678 console.log(preprocessNumber('0612-345-678')); // 0612345678 console.log(preprocessNumber(' 00212 612 345 678 ')); // 0612345678This function removes formatting characters and leading prefixes for pattern validation.
4. Comprehensive Validation Function
Combine preprocessing and regex validation into a single function for streamlined validation.
const patterns = { landline: /^528[89]\d{5}$/, mobile: /^(?:6[0-79]|68[0-247-9]|7[0167]|72[0-4]|75[01]|78[0-3])\d{7}$/, tollFree: /^80[0-7]\d{6}$/, premiumRate: /^89\d{7}$/ }; function validateWesternSaharaNumber(number, type = 'any') { try { const preprocessed = preprocessNumber(number); const cleaned = preprocessed.replace(/^0/, ''); // Remove leading 0 for pattern matching if (type === 'any') { return Object.values(patterns).some(pattern => pattern.test(cleaned)); } return patterns[type] && patterns[type].test(cleaned); } catch (error) { return false; } } // Example usage with detailed results function validateWithDetails(number, type = 'any') { try { const preprocessed = preprocessNumber(number); const cleaned = preprocessed.replace(/^0/, ''); const results = { valid: false, matchedType: null, formatted: { local: preprocessed, international: '+212' + cleaned } }; if (type === 'any') { for (const [typeKey, pattern] of Object.entries(patterns)) { if (pattern.test(cleaned)) { results.valid = true; results.matchedType = typeKey; break; } } } else { results.valid = patterns[type] && patterns[type].test(cleaned); results.matchedType = results.valid ? type : null; } return results; } catch (error) { return { valid: false, error: error.message }; } } // Example usage console.log(validateWesternSaharaNumber('+212528812345', 'landline')); // true console.log(validateWesternSaharaNumber('0612345678', 'mobile')); // true console.log(validateWesternSaharaNumber('800123456', 'tollFree')); // true console.log(validateWesternSaharaNumber('0683123456', 'mobile')); // false console.log(validateWithDetails('0612345678')); // { valid: true, matchedType: 'mobile', formatted: { local: '0612345678', international: '+212612345678' } }Service Number Costs & Restrictions:
+212-80-xxxxxxx. Used for customer service, government helplines, public information.+212-89-xxxxxxx. Used for professional consulting, information services, entertainment. Costs vary by service—check operator rate cards.5. Error Handling and User Feedback
Provide clear error messages in multiple languages to guide users.
const errorMessages = { en: { invalidFormat: 'Invalid phone number format. Expected 10 digits starting with 05, 06, or 07.', invalidPrefix: 'Invalid operator prefix. Check the first 3 digits.', tooShort: 'Phone number is too short. Enter 10 digits.', tooLong: 'Phone number is too long. Enter 10 digits.', invalidLandline: 'Invalid landline number. Western Sahara landlines start with 5288 or 5289.', invalidMobile: 'Invalid mobile number. Check the operator prefix.', invalidTollFree: 'Invalid toll-free number. Format should be 080xxxxxxx.', invalidPremium: 'Invalid premium rate number. Format should be 089xxxxxxx.', nullOrEmpty: 'Phone number is required.', invalidCharacters: 'Phone number contains invalid characters.' }, fr: { invalidFormat: 'Format de numéro de téléphone invalide. 10 chiffres attendus commençant par 05, 06 ou 07.', invalidPrefix: 'Préfixe opérateur invalide. Vérifiez les 3 premiers chiffres.', tooShort: 'Le numéro de téléphone est trop court. Saisissez 10 chiffres.', tooLong: 'Le numéro de téléphone est trop long. Saisissez 10 chiffres.', invalidLandline: 'Numéro fixe invalide. Les lignes fixes du Sahara Occidental commencent par 5288 ou 5289.', invalidMobile: 'Numéro mobile invalide. Vérifiez le préfixe opérateur.', invalidTollFree: 'Numéro gratuit invalide. Le format doit être 080xxxxxxx.', invalidPremium: 'Numéro surtaxé invalide. Le format doit être 089xxxxxxx.', nullOrEmpty: 'Le numéro de téléphone est requis.', invalidCharacters: 'Le numéro de téléphone contient des caractères invalides.' }, ar: { invalidFormat: 'تنسيق رقم الهاتف غير صالح. يجب أن يتكون من 10 أرقام تبدأ بـ 05 أو 06 أو 07.', invalidPrefix: 'بادئة المشغل غير صالحة. تحقق من الأرقام الثلاثة الأولى.', tooShort: 'رقم الهاتف قصير جدًا. أدخل 10 أرقام.', tooLong: 'رقم الهاتف طويل جدًا. أدخل 10 أرقام.', nullOrEmpty: 'رقم الهاتف مطلوب.', invalidCharacters: 'رقم الهاتف يحتوي على أحرف غير صالحة.' } }; function getErrorType(number, type) { if (!number || number.trim().length === 0) return 'nullOrEmpty'; try { const cleaned = preprocessNumber(number).replace(/^0/, ''); if (cleaned.length < 9) return 'tooShort'; if (cleaned.length > 9) return 'tooLong'; if (type === 'landline' && !patterns.landline.test(cleaned)) return 'invalidLandline'; if (type === 'mobile' && !patterns.mobile.test(cleaned)) return 'invalidMobile'; if (type === 'tollFree' && !patterns.tollFree.test(cleaned)) return 'invalidTollFree'; if (type === 'premiumRate' && !patterns.premiumRate.test(cleaned)) return 'invalidPremium'; // Check prefix for general validation const prefix = cleaned.substring(0, 2); if (!['52', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '75', '76', '77', '78', '80', '89'].includes(prefix)) { return 'invalidPrefix'; } return 'invalidFormat'; } catch { return 'invalidCharacters'; } } function validateAndProvideFeedback(number, type = 'any', language = 'en') { const messages = errorMessages[language] || errorMessages.en; if (!validateWesternSaharaNumber(number, type)) { const errorType = getErrorType(number, type); return { valid: false, error: messages[errorType] || messages.invalidFormat }; } const details = validateWithDetails(number, type); return { valid: true, ...details }; } // Example usage console.log(validateAndProvideFeedback('0612345678', 'mobile', 'en')); // { valid: true, matchedType: 'mobile', formatted: {...} } console.log(validateAndProvideFeedback('0691234567', 'mobile', 'fr')); // { valid: false, error: 'Numéro mobile invalide. Vérifiez le préfixe opérateur.' } console.log(validateAndProvideFeedback('123', 'any', 'ar')); // { valid: false, error: 'رقم الهاتف قصير جدًا. أدخل 10 أرقام.' }This approach enhances user experience by providing specific, actionable feedback on validation failures in the user's preferred language.
6. Best Practices for Phone Number Validation
Input Handling:
0__ __ __ __ __Performance Optimization:
Security Considerations:
escapeHtml(phoneNumber)Database Storage:
+212612345678) for consistency and portabilitycountry_code,area_code,subscriber_numberfor complex queriesTesting Strategy:
Regulatory Updates and Considerations
Monitor ANRT regulations for changes to the numbering plan, licensing requirements, and policies. Find updates on the ANRT Official Website.
Recent Updates (as of October 2025):
Licensing & Compliance Requirements:
Compliance Checklist for Telecommunications Systems:
As noted in afrol.com, Maroc Telecom's investment in a fiber optic line extending through Western Sahara into Mauritania signifies a growing emphasis on connectivity in the region (note: article date not verified; infrastructure details subject to change).
Conclusion
Follow these guidelines to implement and maintain telecommunications systems that integrate with Western Sahara's infrastructure and regulatory framework.
Key Takeaways:
Next Steps:
Additional Resources: