This comprehensive guide covers Guyana's phone numbering system, providing developers with everything needed for seamless integration with applications and services. Whether you're building telecommunications software, validating user input with phone number validation, or managing international SMS communications, this resource covers number formats, dialing procedures, validation techniques, best practices, and regulatory considerations specific to Guyana's +592 country code.
Quick Reference
Country: Guyana 🇬🇾
Country Code: +592
International Prefix (Outgoing): 001
International Prefix (Incoming – from USA): 011
National Prefix: None
National Significant Number (NSN): 7 digits
Standard Format (E.164): +592 XXXXXXX
Timezone: UTC-4 (no daylight saving time)
Best Practice: Always store phone numbers in the international E.164 format (+592XXXXXXX) for optimal compatibility and interoperability.
Guyana's Telecommunications Landscape
Guyana's telecommunications sector has undergone significant liberalization since October 2020, fostering competition and growth. The market is primarily served by major operators including GT&T (Guyana Telephone & Telegraph Company) for landline and mobile services, and Digicel Guyana for mobile services.
Developer Impact: When implementing validation or carrier-specific routing:
Number portability may allow users to switch carriers while retaining their number.
Treat prefix-based carrier detection as informational only, not definitive.
Contact the Telecommunications Agency for current operator allocations if carrier identification is critical to your application.
Number Formats and Structure
NSN (National Significant Number): The subscriber number portion excluding the country code, consisting of all digits needed to route a call within the country. For Guyana, this is always 7 digits.
Guyana uses a closed numbering plan with a uniform 7-digit NSN structure across the country. No area codes are used within Guyana, simplifying both domestic and international dialing.
The first digit of the 7-digit number indicates the service type:
81-89, 90-899, 901-9007, 9009-999: Reserved or unallocated
Validation logic should reject numbers starting with these prefixes to prevent false positives.
How to Dial Guyana Phone Numbers
Domestic Calls
Local Calls: Dial the 7-digit number directly (works for all call types: landline-to-landline, mobile-to-mobile, landline-to-mobile, and mobile-to-landline).
No trunk prefix required: Guyana's closed numbering plan does not require a national prefix (trunk code) for domestic calls.
International Calls to and from Guyana
Outgoing from Guyana: Dial 001 + Country Code + Number
Examples:
To USA: 001 1 212 555 0123
To UK: 001 44 20 7946 0958
To Canada: 001 1 416 555 0199
Incoming to Guyana:
From Country
Prefix
Example
USA/Canada
011 + 592 + 7-digit number
011 592 222 1234
UK
00 + 592 + 7-digit number
00 592 222 1234
Australia
0011 + 592 + 7-digit number
0011 592 222 1234
Most of Europe
00 + 592 + 7-digit number
00 592 222 1234
Check your originating country's international dialing prefix if not listed above.
Phone Number Validation for Guyana (+592)
Why Validation Matters:
Prevents failed delivery of SMS/voice calls, reducing costs and improving user experience.
Ensures data integrity in customer databases.
Blocks fraudulent or malformed numbers that could exploit billing systems.
Enables accurate routing and carrier selection.
Use regular expressions to validate Guyanese phone numbers effectively:
Storage: Always store numbers in E.164 format (+592XXXXXXX). This ensures consistency and facilitates integration with various systems. Consider storing the original user input alongside the E.164 version for auditing and troubleshooting. Adding metadata about the number type (landline, mobile, etc.) can also be beneficial.
Database Schema Recommendations:
SQL
CREATE TABLE contacts (
id SERIAL PRIMARY KEY,
phone_e164 VARCHAR(15) NOT NULL, -- E.164 format: +592XXXXXXX
phone_original VARCHAR(50), -- User's original input
phone_type VARCHAR(20), -- landline, mobile, tollFree, premiumRate
phone_verified BOOLEANDEFAULTFALSE,
verified_at TIMESTAMP,
country_code VARCHAR(3) DEFAULT'592',
created_at TIMESTAMPDEFAULT NOW(),
INDEX idx_phone_e164 (phone_e164)
);
Display: Format numbers appropriately for display based on user locale. For local display within Guyana, consider formats like XXX-XXXX. For international display, use the full E.164 format (+592 XXX XXXX).
Validation Pipeline: Implement a comprehensive validation pipeline that includes format checking, length verification, prefix validation, and potentially connectivity testing. Regularly review and update your validation rules to accommodate any changes in the numbering plan.
Timezone Considerations: Guyana operates on UTC-4 year-round (no daylight saving time). When scheduling calls or SMS:
Convert the user's local time to UTC-4 before scheduling.
Respect local business hours (typically 8:00 – 17:00 UTC-4 for business contacts).
Consider implementing "quiet hours" (22:00 – 08:00 local time) to avoid disturbing recipients.
Store all timestamps in UTC in your database and convert to Guyana time for display/scheduling.
Python Implementation Examples
Python
import re
from typing importOptional, Tuplefrom datetime import datetime
import pytz
# Comprehensive validation patterns
PATTERNS = {
'landline': re.compile(r'^2[1-9]\d{5}$'),
'mobile': re.compile(r'^(6\d{6}|7[0-5]\d{5})$'),
'tollFree': re.compile(r'^800\d{4}$'),
'premiumRate': re.compile(r'^9008\d{3}$')
}
defformat_guyana_number(local_number: str) -> str:
"""Convert local number to E.164 format."""
cleaned = re.sub(r'\D', '', local_number)
# Remove country code if already presentif cleaned.startswith('592'):
cleaned = cleaned[3:]
iflen(cleaned) != 7:
raise ValueError(f"Invalid length: expected 7 digits, got {len(cleaned)}")
returnf"+592{cleaned}"defformat_for_display(e164_number: str, local: bool = False) -> str:
"""Format E.164 number for display."""
cleaned = e164_number.replace('+', '').replace('592', '', 1)
if local:
returnf"{cleaned[:3]}-{cleaned[3:]}"returnf"+592 {cleaned[:3]}-{cleaned[3:]}"defdetect_number_type(number: str) -> Optional[str]:
"""Auto-detect the type of a Guyana phone number."""
cleaned = re.sub(r'\D', '', number)
if cleaned.startswith('592'):
cleaned = cleaned[3:]
iflen(cleaned) != 7:
returnNonefor number_type, pattern in PATTERNS.items():
if pattern.match(cleaned):
return number_type
returnNone# Reserved or invalid rangedefvalidate_guyana_number(number: str, number_type: Optional[str] = None) -> Tuple[bool, Optional[str]]:
"""
Validate a Guyana phone number.
Args:
number: Phone number to validate
number_type: Expected type (landline, mobile, tollFree, premiumRate) or None to auto-detect
Returns:
Tuple of (is_valid, detected_type)
"""
cleaned = re.sub(r'\D', '', number)
# Strip country code if presentif cleaned.startswith('592'):
cleaned = cleaned[3:]
iflen(cleaned) != 7:
returnFalse, None
detected_type = detect_number_type(cleaned)
if number_type:
# Validate against specified type
pattern = PATTERNS.get(number_type)
ifnot pattern:
returnFalse, Nonereturn pattern.match(cleaned) isnotNone, detected_type
# No type specified, any valid type passesreturn detected_type isnotNone, detected_type
defis_within_guyana_business_hours(check_time: datetime = None) -> bool:
"""Check if current time (or specified time) is within Guyana business hours."""
guyana_tz = pytz.timezone('America/Guyana') # UTC-4if check_time isNone:
check_time = datetime.now(pytz.UTC)
local_time = check_time.astimezone(guyana_tz)
# Business hours: 8 AM – 5 PM, Monday-Fridayif local_time.weekday() >= 5: # Saturday or SundayreturnFalsereturn8 <= local_time.hour < 17# Example using popular phonenumbers librarytry:
import phonenumbers
defvalidate_with_phonenumbers(number: str) -> dict:
"""Validate using Google's libphonenumber."""try:
parsed = phonenumbers.parse(number, "GY")
return {
'valid': phonenumbers.is_valid_number(parsed),
'possible': phonenumbers.is_possible_number(parsed),
'type': phonenumbers.number_type(parsed),
'e164': phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164),
'international': phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
}
except phonenumbers.NumberParseException as e:
return {'valid': False, 'error': str(e)}
except ImportError:
# phonenumbers library not availablepass# Example usage:if __name__ == "__main__":
test_numbers = [
'2221234', # Valid landline'+5926123456', # Valid mobile'7612345', # Invalid (reserved range)'800-1234'# Valid toll-free
]
for num in test_numbers:
is_valid, num_type = validate_guyana_number(num)
print(f"{num}: valid={is_valid}, type={num_type}")
if is_valid:
print(f" E.164: {format_guyana_number(num)}")
Regulatory Compliance and SMS Guidelines
Telecommunications Act of 2016
The Telecommunications Act of 2016 governs Guyana's telecommunications sector. Key compliance considerations for developers:
Data Storage and Processing:
Obtain explicit consent before storing phone numbers for marketing purposes.
Implement secure storage with encryption for phone number databases.
Provide users the ability to update or delete their phone number data (right to erasure).
Maintain audit logs of phone number access and modifications.
International Data Protection:
GDPR Compliance (if serving EU users): Phone numbers are considered personal data under GDPR. Ensure:
Legal basis for processing (consent, contract, or legitimate interest).
Data minimization – collect only necessary phone number data.
Privacy notices explaining how phone numbers are used.
Data subject rights (access, rectification, erasure, and portability).
Data protection impact assessments for high-risk processing.
Cross-border data transfers: If storing Guyana phone numbers outside the country, ensure adequate safeguards (standard contractual clauses or adequacy decisions).
Avoid unsolicited marketing to mobile numbers without prior consent.
Record Retention:
Keep records of consent for a minimum of 2 years after the relationship ends.
Document the source and date of phone number collection.
For current regulatory requirements, consult the Telecommunications Agency and legal counsel, especially if processing phone numbers at scale or for sensitive purposes. For SMS delivery best practices, see our SMS compliance guide.
Error Handling and Edge Cases
Common Edge Cases to Handle
Empty or null input: Return early with a validation error.
Wrong length: Numbers too short (<7 digits) or too long (>15 digits with country code).
Invalid characters: Letters, special characters beyond +, -, (, ), and spaces.
Country code variations: Handle +592, 592, and no country code.
When validating large batches of phone numbers (>1000 records):
Optimization Strategies:
Compile regex patterns once and reuse them (avoid recompiling in loops).
Use batch processing with async/await for I/O operations.
Implement caching for previously validated numbers.
Consider using compiled validation libraries (e.g., libphonenumber) for performance.
Parallelize validation across multiple workers/threads for very large datasets.
JavaScript
// Batch validation exampleasyncfunctionvalidateBatch(numbers, batchSize = 100) {
const results = [];
for (let i = 0; i < numbers.length; i += batchSize) {
const batch = numbers.slice(i, i + batchSize);
// Process batch in parallelconst batchResults = awaitPromise.all(
batch.map(number =>Promise.resolve(processGuyanaNumber(number)))
);
results.push(...batchResults);
// Optional: Progress callbackif (i % 1000 === 0) {
console.log(`Processed ${i}/${numbers.length} numbers`);
}
}
return results;
}
This comprehensive guide equips developers with the knowledge and tools to handle Guyana phone numbers effectively. By following the best practices and staying informed about regulatory updates, you can ensure seamless integration and reliable communication within your applications.
Frequently asked questions
The country code for Guyana is +592. This code is required when dialing to Guyana from any other country. Remember to precede the country code with the appropriate international prefix (e.g., 011 from the USA).
Always store Guyanese phone numbers in the international E.164 format (+592XXXXXXX). This standardized format ensures compatibility across different systems and simplifies integration with telecommunication services. Storing additional metadata like number type can also be beneficial.
To make international calls from Guyana, use the international prefix 001 followed by the country code and the local number. For example, to call the USA, dial 001 1 212 555 0123.
Guyana does not have a national prefix. You dial the 7-digit National Significant Number (NSN) directly for local calls.
All Guyanese phone numbers have a 7-digit National Significant Number (NSN), regardless of whether they are landlines or mobile numbers. There are no area codes within Guyana.
Guyana utilizes a closed numbering plan, meaning there are no separate area codes within the country. This simplifies dialing, as you only need the 7-digit NSN for any call within Guyana.
The E.164 format for Guyana numbers is +592XXXXXXX, where X represents the seven digits of the National Significant Number (NSN). It's the internationally recommended format for storing phone numbers.
Use the regular expression /^2[1-9]\d{5}$/ to validate a Guyana landline number. This regex ensures the number starts with 2, followed by a digit from 1 to 9, and then five more digits.
Guyanese mobile numbers can be validated using the regex /^(6\d{6}|7[0-5]\d{5})$/. This checks for numbers starting with 6 followed by six digits, or starting with 70 to 75 followed by five digits.
For local display, format numbers as XXX-XXXX. For international display, use the full E.164 format (+592 XXX XXXX) for better clarity and recognition.
You should always store phone numbers in E.164 format (+592XXXXXXX) for consistency and interoperability with various systems and services. It's best practice for database storage and data exchange.
Guyana's phone numbers use prefixes to indicate service type: '2' for landlines, '6' and '7[0-5]' for mobile, '8' for toll-free, and '9' for premium-rate numbers.
Refer to the Telecommunications Agency's official website (https://telecoms.gov.gy/) for the latest regulations and licensing information in Guyana's telecommunications sector.
Dial the 7-digit number directly. No area codes or prefixes are needed for local calls within Guyana.
This comprehensive guide covers Guyana's phone numbering system, providing developers with everything needed for seamless integration with applications and services. Whether you're building telecommunications software, validating user input with phone number validation, or managing international SMS communications, this resource covers number formats, dialing procedures, validation techniques, best practices, and regulatory considerations specific to Guyana's +592 country code.
Quick Reference
Best Practice: Always store phone numbers in the international E.164 format (+592XXXXXXX) for optimal compatibility and interoperability.
Guyana's Telecommunications Landscape
Guyana's telecommunications sector has undergone significant liberalization since October 2020, fostering competition and growth. The market is primarily served by major operators including GT&T (Guyana Telephone & Telegraph Company) for landline and mobile services, and Digicel Guyana for mobile services.
Developer Impact: When implementing validation or carrier-specific routing:
Number Formats and Structure
NSN (National Significant Number): The subscriber number portion excluding the country code, consisting of all digits needed to route a call within the country. For Guyana, this is always 7 digits.
Guyana uses a closed numbering plan with a uniform 7-digit NSN structure across the country. No area codes are used within Guyana, simplifying both domestic and international dialing.
The first digit of the 7-digit number indicates the service type:
2[1-9]XXXXXX(e.g., 2221234)20XXXXXrange is reserved and not allocated for public use6XXXXXXor7[0-5]XXXXX(e.g., 6123456, 7012345)800XXXX(e.g., 8001234)9008XXX(e.g., 9008123)Reserved/Unallocated Ranges:
Validation logic should reject numbers starting with these prefixes to prevent false positives.
How to Dial Guyana Phone Numbers
Domestic Calls
International Calls to and from Guyana
Outgoing from Guyana: Dial
001 + Country Code + NumberExamples:
001 1 212 555 0123001 44 20 7946 0958001 1 416 555 0199Incoming to Guyana:
011 + 592 + 7-digit number011 592 222 123400 + 592 + 7-digit number00 592 222 12340011 + 592 + 7-digit number0011 592 222 123400 + 592 + 7-digit number00 592 222 1234Check your originating country's international dialing prefix if not listed above.
Phone Number Validation for Guyana (+592)
Why Validation Matters:
Use regular expressions to validate Guyanese phone numbers effectively:
// Landline const landlineRegex = /^2[1-9]\d{5}$/; // Mobile const mobileRegex = /^(6\d{6}|7[0-5]\d{5})$/; // Toll-free const tollFreeRegex = /^800\d{4}$/; // Premium Rate const premiumRateRegex = /^9008\d{3}$/; // Comprehensive E.164 validation with country code function validateE164GuyanaNumber(number) { // Accept +592 or 592 prefix const e164Regex = /^\+?592(2[1-9]\d{5}|6\d{6}|7[0-5]\d{5}|800\d{4}|9008\d{3})$/; return e164Regex.test(number.replace(/[\s\-\(\)]/g, '')); } // Auto-detect number type function detectNumberType(number) { const cleaned = number.replace(/\D/g, ''); const nsn = cleaned.startsWith('592') ? cleaned.substring(3) : cleaned; if (nsn.length !== 7) return null; if (/^2[1-9]\d{5}$/.test(nsn)) return 'landline'; if (/^6\d{6}$/.test(nsn)) return 'mobile'; if (/^7[0-5]\d{5}$/.test(nsn)) return 'mobile'; if (/^800\d{4}$/.test(nsn)) return 'tollFree'; if (/^9008\d{3}$/.test(nsn)) return 'premiumRate'; return null; // Invalid or reserved range } function validateGuyanaNumber(number, type) { const cleanedNumber = number.replace(/\D/g, ''); // Remove non-digit characters // Strip country code if present const nsn = cleanedNumber.startsWith('592') ? cleanedNumber.substring(3) : cleanedNumber; switch (type) { case 'landline': return landlineRegex.test(nsn); case 'mobile': return mobileRegex.test(nsn); case 'tollFree': return tollFreeRegex.test(nsn); case 'premiumRate': return premiumRateRegex.test(nsn); default: return false; } } // Example usage: console.log(validateGuyanaNumber('2221234', 'landline')); // true console.log(validateGuyanaNumber('+5926123456', 'mobile')); // true (after cleaning) console.log(validateGuyanaNumber('800-1234', 'tollFree')); // true (after cleaning) console.log(validateE164GuyanaNumber('+5922221234')); // true console.log(detectNumberType('5926123456')); // 'mobile' console.log(detectNumberType('5927612345')); // null (reserved range)Implementation Best Practices
Storage: Always store numbers in E.164 format (+592XXXXXXX). This ensures consistency and facilitates integration with various systems. Consider storing the original user input alongside the E.164 version for auditing and troubleshooting. Adding metadata about the number type (landline, mobile, etc.) can also be beneficial.
Database Schema Recommendations:
CREATE TABLE contacts ( id SERIAL PRIMARY KEY, phone_e164 VARCHAR(15) NOT NULL, -- E.164 format: +592XXXXXXX phone_original VARCHAR(50), -- User's original input phone_type VARCHAR(20), -- landline, mobile, tollFree, premiumRate phone_verified BOOLEAN DEFAULT FALSE, verified_at TIMESTAMP, country_code VARCHAR(3) DEFAULT '592', created_at TIMESTAMP DEFAULT NOW(), INDEX idx_phone_e164 (phone_e164) );Display: Format numbers appropriately for display based on user locale. For local display within Guyana, consider formats like
XXX-XXXX. For international display, use the full E.164 format (+592 XXX XXXX).Validation Pipeline: Implement a comprehensive validation pipeline that includes format checking, length verification, prefix validation, and potentially connectivity testing. Regularly review and update your validation rules to accommodate any changes in the numbering plan.
Timezone Considerations: Guyana operates on UTC-4 year-round (no daylight saving time). When scheduling calls or SMS:
Python Implementation Examples
import re from typing import Optional, Tuple from datetime import datetime import pytz # Comprehensive validation patterns PATTERNS = { 'landline': re.compile(r'^2[1-9]\d{5}$'), 'mobile': re.compile(r'^(6\d{6}|7[0-5]\d{5})$'), 'tollFree': re.compile(r'^800\d{4}$'), 'premiumRate': re.compile(r'^9008\d{3}$') } def format_guyana_number(local_number: str) -> str: """Convert local number to E.164 format.""" cleaned = re.sub(r'\D', '', local_number) # Remove country code if already present if cleaned.startswith('592'): cleaned = cleaned[3:] if len(cleaned) != 7: raise ValueError(f"Invalid length: expected 7 digits, got {len(cleaned)}") return f"+592{cleaned}" def format_for_display(e164_number: str, local: bool = False) -> str: """Format E.164 number for display.""" cleaned = e164_number.replace('+', '').replace('592', '', 1) if local: return f"{cleaned[:3]}-{cleaned[3:]}" return f"+592 {cleaned[:3]}-{cleaned[3:]}" def detect_number_type(number: str) -> Optional[str]: """Auto-detect the type of a Guyana phone number.""" cleaned = re.sub(r'\D', '', number) if cleaned.startswith('592'): cleaned = cleaned[3:] if len(cleaned) != 7: return None for number_type, pattern in PATTERNS.items(): if pattern.match(cleaned): return number_type return None # Reserved or invalid range def validate_guyana_number(number: str, number_type: Optional[str] = None) -> Tuple[bool, Optional[str]]: """ Validate a Guyana phone number. Args: number: Phone number to validate number_type: Expected type (landline, mobile, tollFree, premiumRate) or None to auto-detect Returns: Tuple of (is_valid, detected_type) """ cleaned = re.sub(r'\D', '', number) # Strip country code if present if cleaned.startswith('592'): cleaned = cleaned[3:] if len(cleaned) != 7: return False, None detected_type = detect_number_type(cleaned) if number_type: # Validate against specified type pattern = PATTERNS.get(number_type) if not pattern: return False, None return pattern.match(cleaned) is not None, detected_type # No type specified, any valid type passes return detected_type is not None, detected_type def is_within_guyana_business_hours(check_time: datetime = None) -> bool: """Check if current time (or specified time) is within Guyana business hours.""" guyana_tz = pytz.timezone('America/Guyana') # UTC-4 if check_time is None: check_time = datetime.now(pytz.UTC) local_time = check_time.astimezone(guyana_tz) # Business hours: 8 AM – 5 PM, Monday-Friday if local_time.weekday() >= 5: # Saturday or Sunday return False return 8 <= local_time.hour < 17 # Example using popular phonenumbers library try: import phonenumbers def validate_with_phonenumbers(number: str) -> dict: """Validate using Google's libphonenumber.""" try: parsed = phonenumbers.parse(number, "GY") return { 'valid': phonenumbers.is_valid_number(parsed), 'possible': phonenumbers.is_possible_number(parsed), 'type': phonenumbers.number_type(parsed), 'e164': phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164), 'international': phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.INTERNATIONAL) } except phonenumbers.NumberParseException as e: return {'valid': False, 'error': str(e)} except ImportError: # phonenumbers library not available pass # Example usage: if __name__ == "__main__": test_numbers = [ '2221234', # Valid landline '+5926123456', # Valid mobile '7612345', # Invalid (reserved range) '800-1234' # Valid toll-free ] for num in test_numbers: is_valid, num_type = validate_guyana_number(num) print(f"{num}: valid={is_valid}, type={num_type}") if is_valid: print(f" E.164: {format_guyana_number(num)}")Regulatory Compliance and SMS Guidelines
Telecommunications Act of 2016
The Telecommunications Act of 2016 governs Guyana's telecommunications sector. Key compliance considerations for developers:
Data Storage and Processing:
International Data Protection:
GDPR Compliance (if serving EU users): Phone numbers are considered personal data under GDPR. Ensure:
Cross-border data transfers: If storing Guyana phone numbers outside the country, ensure adequate safeguards (standard contractual clauses or adequacy decisions).
SMS/Voice Communication:
Record Retention:
For current regulatory requirements, consult the Telecommunications Agency and legal counsel, especially if processing phone numbers at scale or for sensitive purposes. For SMS delivery best practices, see our SMS compliance guide.
Error Handling and Edge Cases
Common Edge Cases to Handle
Enhanced Error Handling Implementation
const ErrorCodes = { EMPTY_INPUT: 'EMPTY_INPUT', INVALID_LENGTH: 'INVALID_LENGTH', INVALID_CHARACTERS: 'INVALID_CHARACTERS', INVALID_COUNTRY_CODE: 'INVALID_COUNTRY_CODE', RESERVED_RANGE: 'RESERVED_RANGE', INVALID_PREFIX: 'INVALID_PREFIX', UNKNOWN_ERROR: 'UNKNOWN_ERROR' }; function processGuyanaNumber(input) { try { // Edge case: empty or null input if (!input || input.trim() === '') { throw { code: ErrorCodes.EMPTY_INPUT, message: 'Phone number cannot be empty' }; } // Remove common formatting but preserve digits and + let cleaned = input.replace(/[\s\-\(\)]/g, ''); // Edge case: invalid characters if (!/^[\+\d]+$/.test(cleaned)) { throw { code: ErrorCodes.INVALID_CHARACTERS, message: 'Phone number contains invalid characters' }; } // Remove country code prefix if present if (cleaned.startsWith('+592')) { cleaned = cleaned.substring(4); } else if (cleaned.startsWith('592')) { cleaned = cleaned.substring(3); } else if (cleaned.startsWith('+')) { throw { code: ErrorCodes.INVALID_COUNTRY_CODE, message: 'Invalid country code (expected +592)' }; } // Edge case: wrong length if (cleaned.length !== 7) { throw { code: ErrorCodes.INVALID_LENGTH, message: `Invalid length: expected 7 digits, got ${cleaned.length}` }; } // Edge case: reserved ranges const firstDigit = cleaned[0]; const firstTwo = cleaned.substring(0, 2); if (['3', '4', '5'].includes(firstDigit)) { throw { code: ErrorCodes.RESERVED_RANGE, message: `Range ${firstDigit}XXXXXX is reserved` }; } if (firstTwo === '20') { throw { code: ErrorCodes.RESERVED_RANGE, message: 'Range 20XXXXX is reserved' }; } if (firstDigit === '7' && parseInt(cleaned[1]) > 5) { throw { code: ErrorCodes.RESERVED_RANGE, message: 'Range 7[6-9]XXXXX is reserved' }; } // Detect type and validate const type = detectNumberType(cleaned); if (!type) { throw { code: ErrorCodes.INVALID_PREFIX, message: 'Invalid number prefix or pattern' }; } return { success: true, e164: `+592${cleaned}`, local: cleaned, type: type, formatted: `+592 ${cleaned.substring(0, 3)}-${cleaned.substring(3)}` }; } catch (error) { console.error(`Error processing number: ${error.message}`); return { success: false, error: error.code || ErrorCodes.UNKNOWN_ERROR, message: error.message || 'Unknown error occurred', input: input }; } } // Unit test examples function runTests() { const testCases = [ { input: '2221234', expected: true, description: 'Valid landline' }, { input: '+5926123456', expected: true, description: 'Valid mobile with country code' }, { input: '800-1234', expected: true, description: 'Valid toll-free with formatting' }, { input: '', expected: false, description: 'Empty input' }, { input: '123', expected: false, description: 'Too short' }, { input: '20123456', expected: false, description: 'Reserved range 20' }, { input: '7612345', expected: false, description: 'Reserved range 76' }, { input: '312345', expected: false, description: 'Reserved prefix 3' }, { input: 'abcd123', expected: false, description: 'Invalid characters' }, { input: '+1 592 2221234', expected: false, description: 'Wrong country code format' } ]; testCases.forEach(test => { const result = processGuyanaNumber(test.input); const passed = result.success === test.expected; console.log(`${passed ? '✓' : '✗'} ${test.description}: ${test.input}`); if (!passed) { console.log(` Expected: ${test.expected}, Got: ${result.success}`); if (!result.success) console.log(` Error: ${result.message}`); } }); }Performance Considerations for Bulk Validation
When validating large batches of phone numbers (>1000 records):
Optimization Strategies:
// Batch validation example async function validateBatch(numbers, batchSize = 100) { const results = []; for (let i = 0; i < numbers.length; i += batchSize) { const batch = numbers.slice(i, i + batchSize); // Process batch in parallel const batchResults = await Promise.all( batch.map(number => Promise.resolve(processGuyanaNumber(number))) ); results.push(...batchResults); // Optional: Progress callback if (i % 1000 === 0) { console.log(`Processed ${i}/${numbers.length} numbers`); } } return results; }This comprehensive guide equips developers with the knowledge and tools to handle Guyana phone numbers effectively. By following the best practices and staying informed about regulatory updates, you can ensure seamless integration and reliable communication within your applications.