phonenumber-library
v1.0.2
Published
A phone number library built on Google's libphonenumber with additional features
Maintainers
Readme
Phone Number Library
A comprehensive phone number library built by Ebenezer Akpas on Google's libphonenumber with additional features and a clean, easy-to-use API.
Features
- Phone number parsing and validation
- Multiple formatting options (E.164, International, National, RFC3966)
- Country name support - Accept country names (e.g., "United States", "United Kingdom") in addition to country codes
- Flexible country name formats - Supports case-insensitive, hyphenated, and spaced country names
- Region-specific validation
- Phone number type detection (Mobile, Fixed Line, etc.)
- TypeScript support with full type definitions
- Comprehensive error handling
- Built on Google's battle-tested libphonenumber
Installation
npm install phonenumber-libraryUsage
Basic Usage
import { PhoneNumber } from 'phonenumber-library';
// Create a phone number instance
const phone = new PhoneNumber('+14155552671');
// Check if valid
if (phone.isValid()) {
console.log('Valid phone number!');
}
// Format in different ways
console.log(phone.formatE164()); // +14155552671
console.log(phone.formatInternational()); // +1 415-555-2671
console.log(phone.formatNational()); // (415) 555-2671
console.log(phone.formatRFC3966()); // tel:+1-415-555-2671With Default Region or Country Name
// Parse with default region code (useful for national numbers)
const phone = new PhoneNumber('4155552671', { defaultRegion: 'US' });
console.log(phone.isValid()); // true
// Parse with country name (case-insensitive, supports hyphens and spaces)
const phone1 = new PhoneNumber('4155552671', { countryName: 'United States' });
const phone2 = new PhoneNumber('4155552671', { countryName: 'united states' });
const phone3 = new PhoneNumber('4155552671', { countryName: 'United-States' });
const phone4 = new PhoneNumber('4155552671', { countryName: 'UNITED STATES' });
// All of the above work the same way!
console.log(phone1.isValid()); // true
console.log(phone2.isValid()); // true
console.log(phone3.isValid()); // true
console.log(phone4.isValid()); // true
// Works with compound country names too
const ukPhone = new PhoneNumber('2071838750', { countryName: 'United Kingdom' });
const ukPhone2 = new PhoneNumber('2071838750', { countryName: 'United-Kingdom' });
const ukPhone3 = new PhoneNumber('2071838750', { countryName: 'Great Britain' });Supported Country Name Formats:
- Case-insensitive:
'United States','united states','UNITED STATES'all work - Hyphenated:
'United-States','United-Kingdom'are supported - Multiple spaces:
'United States'(extra spaces are normalized) - Alternative names:
'USA','UK','Great Britain','America'are all supported
Get Comprehensive Information
const phone = new PhoneNumber('+14155552671');
const info = phone.getInfo();
console.log(info);
// {
// countryCode: 1,
// nationalNumber: '4155552671',
// regionCode: 'US',
// isValid: true,
// type: PhoneNumberType.MOBILE,
// formattedE164: '+14155552671',
// formattedInternational: '+1 415-555-2671',
// formattedNational: '(415) 555-2671'
// }
// Get country name
const countryName = phone.getCountryName();
console.log(countryName); // 'United States'
const ukPhone = new PhoneNumber('+442071838750');
console.log(ukPhone.getCountryName()); // 'United Kingdom'Validation
const phone = new PhoneNumber('+14155552671');
// Basic validation
if (phone.isValid()) {
// ...
}
// Region-specific validation (supports country codes or names)
if (phone.isValidForRegion('US')) {
// ...
}
// Also works with country names
if (phone.isValidForRegion('United States')) {
// ...
}
if (phone.isValidForRegion('United-Kingdom')) {
// ...
}
// Comprehensive validation result
const validation = phone.getValidationResult();
console.log(validation);
// {
// isValid: true,
// isValidForRegion: true,
// possibleNumber: true,
// possibleNumberForType: true
// }Phone Number Types
const phone = new PhoneNumber('+14155552671');
// Check specific types
if (phone.isMobile()) {
console.log('This is a mobile number');
}
if (phone.isFixedLine()) {
console.log('This is a fixed line number');
}
// Get the type
const type = phone.getType();Error Handling
// Strict mode (default) - throws errors for invalid numbers
try {
const phone = new PhoneNumber('invalid');
} catch (error) {
console.error('Invalid phone number:', error.message);
}
// Non-strict mode - allows invalid numbers but marks them as invalid
const phone = new PhoneNumber('invalid', { strictMode: false });
if (!phone.isValid()) {
console.log('Phone number is invalid');
}API Reference
PhoneNumber Class
Constructor
new PhoneNumber(phoneNumber: string | number, options?: PhoneNumberOptions)Parameters:
phoneNumber: The phone number to parse (can be in any format)options: Optional configurationcountryName: Country code (e.g., 'US', 'GB') or country name (e.g., 'United States', 'United Kingdom'). Supports case-insensitive, hyphenated, and spaced formats. Default: 'US'defaultRegion: (Deprecated) UsecountryNameinstead. Default region code (e.g., 'US', 'GB'). Default: 'US'strictMode: Whether to throw errors for invalid numbers. Default: true
Methods
Validation
isValid(): boolean- Check if the phone number is validisValidForRegion(regionCode?: string): boolean- Check if valid for a specific regiongetValidationResult(): ValidationResult- Get comprehensive validation resultisMobile(): boolean- Check if the number is a mobile numberisFixedLine(): boolean- Check if the number is a fixed line
Formatting
formatE164(): string- Format in E.164 format (e.g., +14155552671)formatInternational(): string- Format in international format (e.g., +1 415-555-2671)formatNational(): string- Format in national format (e.g., (415) 555-2671)formatRFC3966(): string- Format in RFC3966 format (e.g., tel:+1-415-555-2671)
Information
getCountryCode(): number | null- Get the country codegetNationalNumber(): string | null- Get the national numbergetRegionCode(): string | null- Get the region codegetCountryName(): string | null- Get the standard country name (e.g., 'United States', 'United Kingdom')getType(): PhoneNumberType | null- Get the phone number typegetInfo(): PhoneNumberInfo- Get comprehensive phone number information
Advanced Usage
Using Individual Components
import {
PhoneNumberParser,
PhoneNumberFormatter,
PhoneNumberValidator
} from 'phonenumber-library';
import { PhoneNumberUtil } from 'google-libphonenumber';
const phoneUtil = PhoneNumberUtil.getInstance();
const parser = new PhoneNumberParser(phoneUtil, { countryName: 'United States' });
const formatter = new PhoneNumberFormatter(phoneUtil);
const validator = new PhoneNumberValidator(phoneUtil);
const phoneNumber = parser.parse('+14155552671');
console.log(formatter.formatE164(phoneNumber));
console.log(validator.isValid(phoneNumber));Using CountryNameResolver
import { CountryNameResolver } from 'phonenumber-library';
// Resolve country names to ISO codes
CountryNameResolver.resolve('United States'); // 'US'
CountryNameResolver.resolve('United-States'); // 'US'
CountryNameResolver.resolve('united states'); // 'US'
CountryNameResolver.resolve('UK'); // 'GB'
CountryNameResolver.resolve('Great Britain'); // 'GB'
// Check if a country name can be resolved
CountryNameResolver.canResolve('United States'); // true
CountryNameResolver.canResolve('InvalidCountry'); // false
// Add custom country name mappings
CountryNameResolver.addMapping('MyCountry', 'MC');
CountryNameResolver.resolve('MyCountry'); // 'MC'Requirements
- Node.js >= 14.0.0
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Acknowledgments
This library is built on top of Google's libphonenumber, which provides the core phone number parsing and validation functionality.
