syntaxility-phone-number-validator
v1.0.2
Published
A comprehensive phone number validation library with carrier detection for 40+ countries
Maintainers
Readme
SyntaxilitY Phone Number Validator
A comprehensive, lightweight phone number validation library with carrier detection support for 200+ countries. Overcome the limitations of other phone number validation libraries with SyntaxilitY Phone Number Validator.
[npm version] [License: MIT] [TypeScript]
Features
- Validate phone numbers from 200+ countries
- Carrier detection for 40+ countries (no API required!)
- International formatting (E.164, International, National)
- Country detection from phone numbers
- Bulk validation support
- Zero external API calls - all data is local
- TypeScript support with full type definitions
- Lightweight and fast
- Both ESM and CommonJS support
Supported Countries for Carrier Detection
We support carrier detection for 40+ countries including:
| Region | Countries | |--------|-----------| | Asia | 🇵🇰 Pakistan, 🇮🇳 India, 🇧🇩 Bangladesh, 🇮🇩 Indonesia, 🇲🇾 Malaysia, 🇵🇭 Philippines, 🇯🇵 Japan, 🇰🇷 South Korea, 🇨🇳 China | | Europe | 🇬🇧 UK, 🇩🇪 Germany, 🇫🇷 France, 🇪🇸 Spain, 🇮🇹 Italy, 🇳🇱 Netherlands, 🇹🇷 Turkey | | Middle East | 🇦🇪 UAE, 🇸🇦 Saudi Arabia, 🇪🇬 Egypt | | Africa | 🇿🇦 South Africa, 🇳🇬 Nigeria | | Oceania | 🇦🇺 Australia |
Note: US and Canada use area codes instead of carrier prefixes, so carrier detection is not available for these regions without external databases.
Installation
npm install syntaxility-phone-number-validatoror
yarn add syntaxility-phone-number-validatorQuick Start
CommonJS
const { validateNumber, formatNumber, bulkValidate } = require('syntaxility-phone-number-validator');
(async () => {
// Validate a single number
const result = await validateNumber('+923001234567', { tryCarrier: true });
console.log(result);
// {
// input: '+923001234567',
// valid: true,
// e164: '+923001234567',
// international: '+92 300 1234567',
// national: '0300 1234567',
// country: 'PK',
// countryName: 'Pakistan',
// countryCallingCode: '92',
// type: 'mobile',
// carrier: 'Jazz'
// }
})();ES Modules
import { validateNumber, formatNumber, bulkValidate } from 'syntaxility-phone-number-validator';
const result = await validateNumber('+447700123456', { tryCarrier: true });
console.log(result.carrier); // 'EE'TypeScript
import { validateNumber, ValidationResult, ValidateOptions } from 'syntaxility-phone-number-validator';
const options: ValidateOptions = {
defaultCountry: 'PK',
tryCarrier: true
};
const result: ValidationResult = await validateNumber('+923001234567', options);
console.log(result.carrier); // 'Jazz'API Reference
validateNumber(input, options?)
Validates a single phone number and returns detailed information.
Parameters:
input(string): Phone number to validateoptions(object, optional):defaultCountry(string): ISO country code (e.g., 'PK', 'US', 'GB')tryCarrier(boolean): Attempt to detect carrier (default: false)
Returns: Promise<ValidationResult>
{
input: string;
valid: boolean;
e164?: string; // E.164 format: +923001234567
international?: string; // International format: +92 300 1234567
national?: string; // National format: 0300 1234567
country?: string; // ISO country code: PK
countryName?: string; // Full name: Pakistan
countryCallingCode?: string; // Country code: 92
type?: string; // mobile | fixed | voip | toll-free | etc.
carrier?: string | null; // Carrier name: Jazz, Zong, etc.
error?: string; // Error message if invalid
}Example:
const result = await validateNumber('+923101234567', { tryCarrier: true });
console.log(result.carrier); // 'Zong'
console.log(result.international); // '+92 310 1234567'bulkValidate(inputs, options?)
Validates multiple phone numbers at once.
Parameters:
inputs(string[]): Array of phone numbersoptions(object, optional): Same asvalidateNumber
Returns: Promise<ValidationResult[]>
Example:
const numbers = [
'+923001234567',
'+447700123456',
'+919312345678'
];
const results = await bulkValidate(numbers, { tryCarrier: true });
results.forEach(r => {
console.log(`${r.input} -> ${r.carrier}`);
});
// +923001234567 -> Jazz
// +447700123456 -> EE
// +919312345678 -> AirtelformatNumber(input, formatType, defaultCountry?)
Formats a phone number in the specified format.
Parameters:
input(string): Phone number to formatformatType(string): One of:'E.164','INTERNATIONAL','NATIONAL'defaultCountry(string, optional): ISO country code
Returns: string | undefined
Example:
formatNumber('+923001234567', 'INTERNATIONAL');
// '+92 300 1234567'
formatNumber('+923001234567', 'NATIONAL');
// '0300 1234567'
formatNumber('+923001234567', 'E.164');
// '+923001234567'detectCountry(input, defaultCountry?)
Detects the country of a phone number.
Parameters:
input(string): Phone numberdefaultCountry(string, optional): Default country to assume
Returns: string | undefined (ISO country code)
Example:
detectCountry('+923001234567'); // 'PK'
detectCountry('+447700123456'); // 'GB'getSupportedCountries()
Returns a list of all supported countries.
Returns: Array of objects containing:
{
country: string; // ISO code: 'PK'
countryName: string; // Full name: 'Pakistan'
callingCode: string; // Calling code: '92'
}Example:
const countries = getSupportedCountries();
console.log(countries.length); // 200+
console.log(countries[0]);
// { country: 'AD', countryName: 'Andorra', callingCode: '376' }Use Cases
E-commerce / Signup Forms
async function validateUserPhone(phoneInput) {
const result = await validateNumber(phoneInput, {
defaultCountry: 'PK',
tryCarrier: true
});
if (!result.valid) {
return { error: 'Invalid phone number' };
}
return {
phone: result.e164,
country: result.countryName,
carrier: result.carrier,
type: result.type
};
}SMS Marketing / Analytics
async function segmentUsersByCarrier(phoneNumbers) {
const results = await bulkValidate(phoneNumbers, { tryCarrier: true });
const byCarrier = {};
results.forEach(r => {
if (r.carrier) {
byCarrier[r.carrier] = (byCarrier[r.carrier] || 0) + 1;
}
});
return byCarrier;
// { Jazz: 1523, Zong: 892, Ufone: 456, Telenor: 789 }
}International Contact Forms
async function normalizeInternationalPhone(input, userCountry) {
const result = await validateNumber(input, {
defaultCountry: userCountry
});
if (result.valid) {
return {
display: result.international,
storage: result.e164,
country: result.countryName
};
}
return null;
}Carrier Coverage by Country
- Jazz (300-309)
- Zong (310-318)
- Ufone (320-337)
- Telenor (340-347)
- EE
- O2
- Vodafone
- Three
- Airtel
- Vodafone Idea
- Jio
- Etisalat
- du
- STC
- Mobily
- Zain
See the full list in our documentation.
Advanced Usage
Custom Validation Logic
async function validateWithBusinessRules(phone) {
const result = await validateNumber(phone, { tryCarrier: true });
if (!result.valid) {
return { valid: false, reason: 'Invalid phone number' };
}
// Only allow mobile numbers
if (result.type !== 'mobile') {
return { valid: false, reason: 'Only mobile numbers allowed' };
}
// Only allow specific carriers
const allowedCarriers = ['Jazz', 'Zong'];
if (result.carrier && !allowedCarriers.includes(result.carrier)) {
return { valid: false, reason: 'Carrier not supported' };
}
return { valid: true, data: result };
}Batch Processing with Error Handling
async function processBatch(phoneNumbers) {
const results = await bulkValidate(phoneNumbers, { tryCarrier: true });
const valid = results.filter(r => r.valid);
const invalid = results.filter(r => !r.valid);
return {
processed: results.length,
valid: valid.length,
invalid: invalid.length,
byCarrier: valid.reduce((acc, r) => {
const carrier = r.carrier || 'Unknown';
acc[carrier] = (acc[carrier] || 0) + 1;
return acc;
}, {}),
errors: invalid.map(r => ({
input: r.input,
error: r.error
}))
};
}Testing
The package includes comprehensive tests covering all supported carriers:
npm testSample test output:
✓ PASS: Pakistan Jazz
✓ PASS: Pakistan Zong
✓ PASS: UK EE
✓ PASS: India Airtel
✓ PASS: UAE Etisalat
...
Total Tests: 66
Passed: 66 (100%)TypeScript Support
Full TypeScript definitions included:
import {
validateNumber,
bulkValidate,
formatNumber,
detectCountry,
getSupportedCountries,
ValidationResult,
ValidateOptions
} from 'syntaxility-phone-number-validator';Contributing
Contributions are welcome! To add more carriers:
- Fork the repository
- Add carrier prefixes to
CARRIER_PREFIXESinsrc/index.ts - Add tests for the new carriers
- Submit a pull request
License
MIT © Tariq Mehmood
Credits
Built with:
- libphonenumber-js - Core phone number validation
Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Roadmap
- [ ] Add more carrier prefixes for additional countries
- [ ] Add carrier detection for US/Canada via external APIs (optional)
- [ ] Add number type detection improvements
- [ ] Add validation rule presets (e.g., "mobile-only", "no-premium")
- [ ] Add phone number suggestions for typos
Made with ❤️ by SyntaxilitY Team
