This library includes phone number lookup and validation, and the geocoding, carrier mapping and timezone mapping functionalities that are available in some of googles libphonenumber libraries.
To reduce the amount of data that needs to be loaded to geocode / carrier map a phone-number for each mapping only the relevant number prefixes are loaded from a binary json file (BSON). When the prefix could not be found in the provided locale the library tries to fall back to
en
as locale.The library supports Node.js only at the moment.
β Check phone number validity
β Check phone number format
β Check phone number carrier name
β Check phone number geolocation (city)
β Check phone number timezone
β Check phone number country code
β High-performance LRU caching with configurable size
β Comprehensive error handling and input validation
β TypeScript support with strict type safety
β Serverless architecture support (AWS Lambda, Cloudflare Workers, Vercel Edge, Deno)
- Increase delivery rate of SMS campaigns by removing invalid phone numbers
- Increase SMS open rate and your marketing IPs reputation
- Protect your website from spam, bots and fake phone numbers
- Protect your product signup form from fake phone numbers
- Protect your website forms from fake phone numbers
- Protect your self from fraud orders and accounts using fake phone numbers
- Integrate phone number verification into your website forms
- Integrate phone number verification into your backoffice administration and order processing
- Integrate phone number verification into your mobile apps
We offer this phone verification and validation and more advanced features
in our Scalable Cloud API Service Offering - You could try it here Phone Number Verification
npm install @devmehq/phone-number-validator-js
or
yarn add @devmehq/phone-number-validator-js
geocoder(phonenumber: PhoneNumber, locale?: GeocoderLocale = 'en'): string | null
- Resolved to the geocode or null if no geocode could be found (e.g. for mobile numbers)carrier(phonenumber: PhoneNumber, locale?: CarrierLocale = 'en'): string | null
- Resolves to the carrier or null if non could be found (e.g. for fixed line numbers)timezones(phonenumber: PhoneNumber): Array<string> | null
- Resolved to an array of timezones or null if non where found.
clearCache(): void
- Clear all cached datagetCacheSize(): number
- Get current cache sizesetCacheSize(size: number): void
- Set maximum cache size (default: 100)
import { geocoder, carrier, timezones, parsePhoneNumberFromString } from '@devmehq/phone-number-validator-js'
const fixedLineNumber = parsePhoneNumberFromString('+41431234567')
const locationEN = geocoder(fixedLineNumber) // Zurich
const locationDE = geocoder(fixedLineNumber, 'de') // ZΓΌrich
const locationIT = geocoder(fixedLineNumber, 'it') // Zurigo
const mobileNumber = parsePhoneNumberFromString('+8619912345678')
const carrierEN = carrier(mobileNumber) // China Telecom
const carrierZH = carrier(mobileNumber, 'zh') // δΈε½η΅δΏ‘
const fixedLineNumber2 = parsePhoneNumberFromString('+49301234567')
const tzones = timezones(fixedLineNumber2) // ['Europe/Berlin']
import {
clearCache,
getCacheSize,
setCacheSize,
geocoder,
parsePhoneNumberFromString
} from '@devmehq/phone-number-validator-js'
// Adjust cache size based on your needs
setCacheSize(50) // Limit to 50 entries
// Monitor cache usage
console.log(`Cache size: ${getCacheSize()}`)
// Perform lookups
const phoneNumber = parsePhoneNumberFromString('+41431234567')
const location = geocoder(phoneNumber)
// Clear cache when needed
if (getCacheSize() > 40) {
clearCache()
}
// For long-running processes, you might want to clear cache periodically
setInterval(() => {
clearCache()
}, 3600000) // Clear every hour
import { geocoder, parsePhoneNumberFromString } from '@devmehq/phone-number-validator-js'
// Invalid phone numbers return null
const invalid = parsePhoneNumberFromString('invalid')
const result = geocoder(invalid) // null
// Undefined/null inputs are handled gracefully
const result2 = geocoder(undefined) // null
const result3 = geocoder(null) // null
import {
geocoder,
carrier,
timezones,
parsePhoneNumberFromString,
PhoneNumber,
GeocoderLocale,
CarrierLocale
} from '@devmehq/phone-number-validator-js'
// Type-safe locale usage
const phoneNumber: PhoneNumber | undefined = parsePhoneNumberFromString('+41431234567')
const locale: GeocoderLocale = 'de'
const location: string | null = geocoder(phoneNumber, locale)
const carrierInfo: string | null = carrier(phoneNumber)
const tzs: string[] | null = timezones(phoneNumber)
// Cache management with types
import { setCacheSize, getCacheSize, clearCache } from '@devmehq/phone-number-validator-js'
const size: number = getCacheSize()
setCacheSize(50)
clearCache()
The library provides a lightweight serverless version that's optimized for edge environments like AWS Lambda, Cloudflare Workers, Vercel Edge Functions, and Deno Deploy.
- 244KB bundle size (minified) - fits well under most size limits
- No Node.js dependencies - runs in any JavaScript environment
- Resource loader pattern - load data from your preferred storage (S3, R2, KV, etc.)
- Same API - drop-in replacement for the standard version
// Use the serverless entry point
import {
setResourceLoader,
parsePhoneNumber,
geocoder,
carrier,
timezones
} from '@devmehq/phone-number-validator-js/serverless'
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3'
import { setResourceLoader, geocoder, parsePhoneNumber } from '@devmehq/phone-number-validator-js/serverless'
const s3 = new S3Client()
// Set up resource loader
setResourceLoader({
async loadResource(path) {
try {
const command = new GetObjectCommand({
Bucket: process.env.RESOURCES_BUCKET,
Key: `phone-validator/${path}`
})
const response = await s3.send(command)
return new Uint8Array(await response.Body.transformToByteArray())
} catch {
return null
}
}
})
// Lambda handler
export async function handler(event) {
const phoneNumber = parsePhoneNumber(event.phone, event.country)
const location = await geocoder(phoneNumber)
return {
statusCode: 200,
body: JSON.stringify({ location })
}
}
import { setResourceLoader, carrier, parsePhoneNumber } from '@devmehq/phone-number-validator-js/serverless'
// Use R2 storage for resources
setResourceLoader({
async loadResource(path) {
const object = await env.RESOURCES_BUCKET.get(`phone-validator/${path}`)
if (!object) return null
const buffer = await object.arrayBuffer()
return new Uint8Array(buffer)
}
})
export default {
async fetch(request, env) {
const url = new URL(request.url)
const phone = url.searchParams.get('phone')
const phoneNumber = parsePhoneNumber(phone)
const carrierInfo = await carrier(phoneNumber)
return Response.json({ carrier: carrierInfo })
}
}
import { setResourceLoader, timezones, parsePhoneNumber } from '@devmehq/phone-number-validator-js/serverless'
// Use Vercel Blob storage
setResourceLoader({
async loadResource(path) {
const response = await fetch(`${process.env.BLOB_URL}/phone-validator/${path}`)
if (!response.ok) return null
const buffer = await response.arrayBuffer()
return new Uint8Array(buffer)
}
})
export const config = { runtime: 'edge' }
export default async function handler(req) {
const { phone } = await req.json()
const phoneNumber = parsePhoneNumber(phone)
const tzs = await timezones(phoneNumber)
return Response.json({ timezones: tzs })
}
The serverless version requires resource files to be deployed separately. Download them from the npm package:
# Extract resource files from the npm package
npm pack @devmehq/phone-number-validator-js
tar -xf devmehq-phone-number-validator-js-*.tgz
cp -r package/resources/* your-storage-location/
Then upload to your preferred storage (S3, R2, Blob storage, etc.) and configure the resource loader accordingly.
- Use caching: The library includes built-in LRU caching
- Deploy resources to the same region as your functions for lower latency
- Consider using CDN for resource files if serving globally
- Use sync loader when possible for better performance:
// Sync loader for environments that support it
setResourceLoader({
loadResourceSync(path) {
// Synchronous loading implementation
return loadFromCacheSync(path)
},
async loadResource(path) {
// Async fallback
return loadFromCacheAsync(path)
}
})
For detailed serverless deployment guides, see SERVERLESS.md.
The library uses tiny-lru for high-performance caching:
- O(1) complexity for cache operations (get, set, delete)
- LRU eviction when cache reaches the size limit
- Configurable cache size to balance memory usage and performance
- <1ms lookups after initial data load
yarn test
Run tests in production mode (suppresses debug logs):
NODE_ENV=production yarn test
Please feel free to open an issue or create a pull request and fix bugs or add features, All contributions are welcome. Thank you!
For issues, questions, or commercial licensing:
π Open an Issue π§ Email Support π Commercial License π Visit Dev.me
Business Source License 1.1 - see LICENSE file for details.
The BSL allows use only for non-production purposes. Here's a comprehensive guide to help you understand when you need a commercial license:
Use Case | Commercial License Required? | Details |
---|---|---|
Personal & Learning | ||
π¬ Exploring phone-number-validator-js for research or learning | β No | Use freely for educational purposes |
π¨ Personal hobby projects (non-commercial) | β No | Build personal tools and experiments |
π§ͺ Testing and evaluation in development environment | β No | Test all features before purchasing |
Development & Prototyping | ||
π‘ Building proof-of-concept applications | β No | Create demos and prototypes |
π οΈ Internal tools (not customer-facing) | β No | Use for internal development tools |
π Open source projects (non-commercial) | β No | Contribute to the community |
Commercial & Production Use | ||
π° Revenue-generating applications | β Yes | Any app that generates income |
βοΈ Software as a Service (SaaS) products | β Yes | Cloud-based service offerings |
π¦ Distributed commercial software | β Yes | Software sold to customers |
π’ Enterprise production systems | β Yes | Business-critical applications |
π Forking for commercial purposes | β Yes | Creating derivative commercial products |
π Production use in any form | β Yes | Live systems serving real users |
Specific Scenarios | ||
π Student projects and coursework | β No | Academic use is encouraged |
ποΈ CI/CD pipelines (for commercial products) | β Yes | Part of commercial development |
π± Phone validation in production APIs | β Yes | Production service usage |
π E-commerce checkout validation | β Yes | Revenue-related validation |
π± Mobile apps (free with ads or paid) | β Yes | Monetized applications |
Ask yourself these questions:
- Will real users interact with this in production? β You need a license
- Will this help generate revenue? β You need a license
- Is this for learning or testing only? β No license needed
- Is this an internal prototype or POC? β No license needed
β¨ Unlimited Usage - Use in all your production applications
π Priority Support - Direct support from our engineering team
π Regular Updates - Get the latest features and improvements
π‘οΈ Legal Protection - Full commercial rights and warranty
π’ Enterprise Ready - Suitable for large-scale deployments
Ready to use phone-number-validator-js in production?
ποΈ Purchase a License - Simple pricing, instant activation
π§ Contact Sales - For enterprise or custom needs