@bernierllc/phone-tools
v1.2.0
Published
Comprehensive phone number manipulation and validation utilities for JavaScript/TypeScript applications
Readme
@bernierllc/phone-tools
Comprehensive phone number manipulation and validation utilities for JavaScript/TypeScript applications. Provides production-ready, locale-aware phone number processing including validation, formatting, parsing, type detection, and country code utilities.
Features
- ✅ International Validation - Country-specific phone number validation
- ✅ Multiple Formats - E.164, international, national, RFC3966
- ✅ Component Parsing - Extract country code, area code, local number
- ✅ Type Detection - Identify mobile, landline, toll-free, VoIP, etc.
- ✅ Privacy Masking - Mask phone numbers for display
- ✅ Text Extraction - Find phone numbers in text
- ✅ Link Generation - Generate tel: and sms: links
- ✅ As-You-Type Formatting - Progressive formatting for user input
- ✅ Batch Operations - Process multiple numbers efficiently
- ✅ Country Utilities - Calling codes, supported countries, examples
Installation
npm install @bernierllc/phone-toolsQuick Start
import {
validatePhoneNumber,
formatPhoneNumber,
parsePhoneNumber,
maskPhoneNumber
} from '@bernierllc/phone-tools';
// Validate
const result = validatePhoneNumber('+12133734253');
console.log(result.isValid); // true
// Format
const formatted = formatPhoneNumber('+12133734253', { format: 'NATIONAL' });
console.log(formatted); // (213) 373-4253
// Parse
const parsed = parsePhoneNumber('+12133734253');
console.log(parsed.country); // US
// Mask for privacy
const masked = maskPhoneNumber('+12133734253');
console.log(masked); // +1 (***) ***-4253API Reference
Validation
validatePhoneNumber(phoneNumber, options?)
Comprehensive phone number validation with detailed results.
const result = validatePhoneNumber('+12133734253');
// {
// isValid: true,
// isPossible: true,
// country: 'US',
// type: 'FIXED_LINE',
// formatted: {
// e164: '+12133734253',
// international: '+1 213 373 4253',
// national: '(213) 373-4253'
// }
// }isValidPhoneNumber(phoneNumber, options?)
Simple boolean validation.
isValidPhoneNumber('+12133734253'); // true
isValidPhoneNumber('123'); // falseisPossiblePhoneNumber(phoneNumber, options?)
Check if number has valid length for its country.
isPossiblePhoneNumber('+12133734253'); // true
isPossiblePhoneNumber('+1'); // false (too short)Formatting
formatPhoneNumber(phoneNumber, options?)
Format phone number to different standards.
formatPhoneNumber('+12133734253', { format: 'E164' });
// '+12133734253'
formatPhoneNumber('+12133734253', { format: 'INTERNATIONAL' });
// '+1 213 373 4253'
formatPhoneNumber('+12133734253', { format: 'NATIONAL' });
// '(213) 373-4253'
formatPhoneNumber('+12133734253', { format: 'RFC3966' });
// 'tel:+12133734253'normalizePhoneNumber(phoneNumber, options?)
Normalize to E.164 format for storage.
normalizePhoneNumber('(213) 373-4253', { defaultCountry: 'US' });
// '+12133734253'getAllFormats(phoneNumber)
Get all format variations at once.
const formats = getAllFormats('+12133734253');
// {
// e164: '+12133734253',
// international: '+1 213 373 4253',
// national: '(213) 373-4253',
// rfc3966: 'tel:+12133734253'
// }Parsing
parsePhoneNumber(phoneNumber, options?)
Parse phone number into components.
const parsed = parsePhoneNumber('+12133734253');
// {
// countryCode: '1',
// nationalNumber: '2133734253',
// areaCode: '213',
// localNumber: '3734253',
// country: 'US',
// type: 'FIXED_LINE'
// }getPhoneNumberType(phoneNumber, options?)
Identify phone number type.
getPhoneNumberType('+12133734253'); // 'FIXED_LINE'
getPhoneNumberType('+16505551234'); // 'MOBILE'getPhoneCountryCode(phoneNumber, options?)
Get country code from phone number.
getPhoneCountryCode('+12133734253'); // 'US'
getPhoneCountryCode('+447400123456'); // 'GB'getCallingCode(phoneNumber)
Get calling code from phone number.
getCallingCode('+12133734253'); // '1'
getCallingCode('+447400123456'); // '44'As-You-Type Formatting
createAsYouTypeFormatter(options?)
Create formatter for progressive input.
const formatter = createAsYouTypeFormatter({ defaultCountry: 'US' });
formatter.input('2'); // '2'
formatter.input('1'); // '21'
formatter.input('3'); // '(213)'
formatter.input('3'); // '(213) 3'
formatter.input('7'); // '(213) 37'
formatter.input('3'); // '(213) 373'
formatter.input('4'); // '(213) 373-4'
formatter.input('2'); // '(213) 373-42'
formatter.input('5'); // '(213) 373-425'
formatter.input('3'); // '(213) 373-4253'
formatter.isValid(); // true
formatter.reset(); // Start overMasking & Privacy
maskPhoneNumber(phoneNumber, options?)
Mask phone number for privacy.
maskPhoneNumber('+12133734253');
// '+1 (***) ***-4253' (default: last 4 visible)
maskPhoneNumber('+12133734253', { visibleDigits: 2 });
// '+1 (***) ***-**53'
maskPhoneNumber('+12133734253', {
visibleDigits: 3,
position: 'start'
});
// '+1 213-***-****'
maskPhoneNumber('+12133734253', { maskChar: 'X' });
// '+1 (XXX) XXX-4253'Text Extraction
extractPhoneNumbers(text, options?)
Extract phone numbers from text.
const text = 'Call me at +1 (213) 373-4253 or 650-555-1234';
extractPhoneNumbers(text);
// ['+12133734253', '+16505551234']replacePhoneNumbers(text, replacer, options?)
Find and replace phone numbers.
const text = 'Contact: +12133734253';
replacePhoneNumbers(text, (phone) => maskPhoneNumber(phone));
// 'Contact: +1 (***) ***-4253'Link Generation
generatePhoneLink(phoneNumber)
Generate tel: link.
generatePhoneLink('+12133734253');
// 'tel:+12133734253'generateSmsLink(phoneNumber, body?)
Generate SMS link.
generateSmsLink('+12133734253');
// 'sms:+12133734253'
generateSmsLink('+12133734253', 'Hello there!');
// 'sms:+12133734253?body=Hello%20there!'Country Utilities
getCountryCallingCode(country)
Get calling code for country.
getCountryCallingCode('US'); // '1'
getCountryCallingCode('GB'); // '44'
getCountryCallingCode('FR'); // '33'getCountriesForCallingCode(callingCode)
Get countries for calling code.
getCountriesForCallingCode('1');
// ['US', 'CA', 'AG', 'AI', ...]getSupportedCountries()
Get all supported countries.
const countries = getSupportedCountries();
// ['US', 'CA', 'GB', 'FR', ...]isCountrySupported(country)
Check if country is supported.
isCountrySupported('US'); // true
isCountrySupported('ZZ'); // falsegetExampleNumber(country)
Get example phone number for country.
getExampleNumber('US'); // '+12015550123'
getExampleNumber('GB'); // '+447400123456'Batch Operations
validatePhoneNumbers(phoneNumbers, options?)
Validate multiple phone numbers.
const phones = ['+12133734253', 'invalid', '+447400123456'];
const results = validatePhoneNumbers(phones);
// [
// { isValid: true, ... },
// { isValid: false, errors: [...] },
// { isValid: true, ... }
// ]formatPhoneNumbers(phoneNumbers, options?)
Format multiple phone numbers.
formatPhoneNumbers(
['+12133734253', '+447400123456'],
{ format: 'INTERNATIONAL' }
);
// ['+1 213 373 4253', '+44 7400 123456']normalizePhoneNumbers(phoneNumbers, options?)
Normalize multiple phone numbers.
normalizePhoneNumbers(
['(213) 373-4253', '(650) 555-1234'],
{ defaultCountry: 'US' }
);
// ['+12133734253', '+16505551234']Comparison
arePhoneNumbersEqual(phoneA, phoneB)
Check if two phone numbers are equivalent.
arePhoneNumbersEqual('+12133734253', '+1 (213) 373-4253'); // true
arePhoneNumbersEqual('+12133734253', '+12133734254'); // falsecomparePhoneNumbers(phoneA, phoneB)
Compare phone numbers for sorting.
comparePhoneNumbers('+12133734253', '+12133734253'); // 0
comparePhoneNumbers('+12133734252', '+12133734253'); // -1
comparePhoneNumbers('+12133734254', '+12133734253'); // 1Error Handling
Functions return null for invalid inputs or use structured error results:
// Safe wrapper functions return PhoneResult<T>
const result = validatePhoneNumberSafe('invalid');
// {
// success: false,
// error: 'Invalid phone number',
// details: {
// code: 'INVALID_FORMAT',
// field: 'phoneNumber'
// }
// }Real-World Examples
Contact Form Validation
function validatePhoneInput(input: string, country: string) {
const result = validatePhoneNumber(input, { defaultCountry: country });
if (!result.isValid) {
return {
valid: false,
error: 'Please enter a valid phone number'
};
}
// Store normalized version
const normalized = normalizePhoneNumber(input, { defaultCountry: country });
return {
valid: true,
value: normalized
};
}Display Formatting
function displayPhone(storedNumber: string, format: 'local' | 'international') {
const phoneFormat = format === 'local' ? 'NATIONAL' : 'INTERNATIONAL';
return formatPhoneNumber(storedNumber, { format: phoneFormat });
}
displayPhone('+12133734253', 'local');
// '(213) 373-4253'
displayPhone('+12133734253', 'international');
// '+1 213 373 4253'Privacy Protection
function displaySecurePhone(phoneNumber: string) {
return maskPhoneNumber(phoneNumber, {
visibleDigits: 4,
position: 'end'
});
}
displaySecurePhone('+12133734253');
// '+1 (***) ***-4253'Click-to-Call
function createCallLink(phoneNumber: string, displayText?: string) {
const link = generatePhoneLink(phoneNumber);
const display = displayText || formatPhoneNumber(phoneNumber, {
format: 'NATIONAL'
});
return `<a href="${link}">${display}</a>`;
}
createCallLink('+12133734253');
// '<a href="tel:+12133734253">(213) 373-4253</a>'TypeScript Support
Fully typed with TypeScript. Import types:
import type {
PhoneValidationOptions,
PhoneValidationResult,
PhoneFormat,
PhoneType,
PhoneComponents,
PhoneResult
} from '@bernierllc/phone-tools';Testing
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests once (no watch)
npm run test:runQuality Standards
- ✅ 91%+ test coverage (statements)
- ✅ 100% function coverage
- ✅ TypeScript strict mode
- ✅ Zero linting errors
- ✅ Production-ready
Dependencies
- libphonenumber-js - Phone number validation engine
- 8.6M+ weekly downloads
- Actively maintained
- Full TypeScript support
- Smaller bundle size than google-libphonenumber (145 KB vs 550 KB)
Integration Status
- Logger: Not applicable (core utility)
- Docs-Suite: Ready (TypeScript documentation)
- NeverHub: Not applicable (pure utility)
License
Copyright (c) 2025 Bernier LLC
This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
See Also
- @bernierllc/sms-sender - SMS sending service (uses phone-tools for validation)
- @bernierllc/validators-phone - Domain validator (uses phone-tools primitives)
- @bernierllc/contact-manager - Contact management (uses phone-tools for normalization)
