Tools for generating example phone numbers and providing real-time formatting as users input phone numbers. These capabilities are essential for building user interfaces, form validation, and demonstrating proper phone number formats.
Generates example phone numbers for a specific region and phone number type, useful for placeholders, testing, and user guidance.
/**
* Get an example phone number, given a region code and a phone number type.
*
* @param regionCode ISO region code (e.g., "SE", "US", "GB")
* @param type Optional phone number type (defaults to a representative example)
* @returns ParsedPhoneNumber object with example number
*/
function getExample(
regionCode: string,
type?: PhoneNumberTypes
): ParsedPhoneNumber;Usage Examples:
import { getExample } from "awesome-phonenumber";
// Get a general example for Sweden
const swedenExample = getExample("SE");
if (swedenExample.valid) {
console.log(swedenExample.number.national); // "08-123 456 78"
console.log(swedenExample.type); // "fixed-line"
}
// Get specific type examples
const mobileSE = getExample("SE", "mobile");
if (mobileSE.valid) {
console.log(mobileSE.number.national); // "070-123 45 67"
console.log(mobileSE.typeIsMobile); // true
}
const fixedLineUS = getExample("US", "fixed-line");
if (fixedLineUS.valid) {
console.log(fixedLineUS.number.national); // "(212) 123-4567"
console.log(fixedLineUS.typeIsFixedLine); // true
}
const tollFreeUS = getExample("US", "toll-free");
if (tollFreeUS.valid) {
console.log(tollFreeUS.number.national); // "(800) 123-4567"
console.log(tollFreeUS.type); // "toll-free"
}Creates an incremental formatter that provides real-time formatting as users type phone numbers.
/**
* Get an instance of the AsYouType class, based on a region code.
*
* @param regionCode The region code to get an AsYouType instance for
* @returns AsYouType instance configured for the specified region
*/
function getAsYouType(regionCode: string): AsYouType;Provides incremental phone number formatting with real-time feedback and editing capabilities.
class AsYouType {
private constructor();
/**
* Add a character to the current input and return the formatted result
* @param char Single character to add
* @returns Formatted phone number string
*/
addChar(char: string): string;
/**
* Get the current formatted number
* @returns Current formatted phone number string
*/
number(): string;
/**
* Remove the last character and return the updated formatted result
* @returns Formatted phone number string after character removal
*/
removeChar(): string;
/**
* Reset the formatter with an optional new number
* @param number Optional starting number
* @returns Formatted result
*/
reset(number?: string): string;
/**
* Get a parsed phone number object from the current input
* @returns ParsedPhoneNumber object
*/
getPhoneNumber(): ParsedPhoneNumber;
}Usage Examples:
import { getAsYouType } from "awesome-phonenumber";
// Create formatter for Sweden
const formatter = getAsYouType("SE");
// Simulate user typing a phone number
console.log(formatter.addChar("0")); // "0"
console.log(formatter.addChar("7")); // "07"
console.log(formatter.addChar("0")); // "070"
console.log(formatter.addChar("7")); // "070-7"
console.log(formatter.addChar("1")); // "070-71"
console.log(formatter.addChar("2")); // "070-712"
console.log(formatter.addChar("3")); // "070-712 3"
console.log(formatter.addChar("4")); // "070-712 34"
console.log(formatter.addChar("5")); // "070-712 34 5"
console.log(formatter.addChar("6")); // "070-712 34 56"
// Get current formatted number
console.log(formatter.number()); // "070-712 34 56"
// Remove last character
console.log(formatter.removeChar()); // "070-712 34 5"
// Get parsed phone number
const parsed = formatter.getPhoneNumber();
if (parsed.valid) {
console.log(parsed.number.e164); // "+46707123456"
}
// Reset with new number
console.log(formatter.reset("08")); // "08"import { getAsYouType } from "awesome-phonenumber";
class PhoneNumberInput {
private formatter: AsYouType;
private inputElement: HTMLInputElement;
constructor(inputElement: HTMLInputElement, regionCode: string) {
this.formatter = getAsYouType(regionCode);
this.inputElement = inputElement;
this.setupEventListeners();
}
private setupEventListeners() {
this.inputElement.addEventListener('input', (e) => {
const input = e.target as HTMLInputElement;
const value = input.value;
const cursorPos = input.selectionStart || 0;
// Reset formatter and rebuild
this.formatter.reset();
let formatted = "";
for (let i = 0; i < value.length; i++) {
const char = value[i];
if (/\d/.test(char)) { // Only add digits
formatted = this.formatter.addChar(char);
}
}
input.value = formatted;
// Restore cursor position (simplified)
const newPos = Math.min(cursorPos, formatted.length);
input.setSelectionRange(newPos, newPos);
});
this.inputElement.addEventListener('keydown', (e) => {
if (e.key === 'Backspace') {
this.formatter.removeChar();
}
});
}
getPhoneNumber() {
return this.formatter.getPhoneNumber();
}
isValid(): boolean {
return this.formatter.getPhoneNumber().valid;
}
}
// Usage
const input = document.getElementById('phone') as HTMLInputElement;
const phoneInput = new PhoneNumberInput(input, 'US');import { getExample, getSupportedRegionCodes } from "awesome-phonenumber";
class ExampleGenerator {
private supportedRegions: string[];
constructor() {
this.supportedRegions = getSupportedRegionCodes();
}
getExamplesForRegion(regionCode: string) {
if (!this.supportedRegions.includes(regionCode)) {
throw new Error(`Region ${regionCode} not supported`);
}
const types: PhoneNumberTypes[] = [
'mobile', 'fixed-line', 'toll-free', 'premium-rate'
];
const examples: Record<string, any> = {};
types.forEach(type => {
const example = getExample(regionCode, type);
if (example.valid) {
examples[type] = {
national: example.number.national,
international: example.number.international,
e164: example.number.e164
};
}
});
return examples;
}
generatePlaceholders(regionCode: string) {
const mobile = getExample(regionCode, 'mobile');
const fixedLine = getExample(regionCode, 'fixed-line');
return {
mobile: mobile.valid ? mobile.number.national : '',
fixedLine: fixedLine.valid ? fixedLine.number.national : ''
};
}
}
const generator = new ExampleGenerator();
console.log(generator.getExamplesForRegion('US'));
// {
// mobile: { national: "(201) 123-4567", international: "+1 201-123-4567", ... },
// fixed-line: { national: "(212) 123-4567", international: "+1 212-123-4567", ... },
// ...
// }import { getAsYouType } from "awesome-phonenumber";
class ValidatingFormatter {
private formatter: AsYouType;
private onValidationChange?: (isValid: boolean, parsed: ParsedPhoneNumber) => void;
constructor(regionCode: string, onValidationChange?: (isValid: boolean, parsed: ParsedPhoneNumber) => void) {
this.formatter = getAsYouType(regionCode);
this.onValidationChange = onValidationChange;
}
input(character: string): string {
const formatted = this.formatter.addChar(character);
this.validateCurrent();
return formatted;
}
backspace(): string {
const formatted = this.formatter.removeChar();
this.validateCurrent();
return formatted;
}
private validateCurrent() {
const parsed = this.formatter.getPhoneNumber();
this.onValidationChange?.(parsed.valid, parsed);
}
getCurrentNumber() {
return this.formatter.getPhoneNumber();
}
clear() {
this.formatter.reset();
this.validateCurrent();
}
}
// Usage with validation feedback
const validator = new ValidatingFormatter('SE', (isValid, parsed) => {
console.log(`Valid: ${isValid}`);
if (isValid) {
console.log(`Type: ${parsed.type}, Country: ${parsed.countryCode}`);
}
});
// Simulate user input
console.log(validator.input('0')); // "0", Valid: false
console.log(validator.input('7')); // "07", Valid: false
console.log(validator.input('0')); // "070", Valid: false
// ... continue until complete numberimport { getExample } from "awesome-phonenumber";
function generateFormPlaceholders(regionCode: string) {
const mobileExample = getExample(regionCode, 'mobile');
const fixedExample = getExample(regionCode, 'fixed-line');
return {
mobile: mobileExample.valid ? `e.g., ${mobileExample.number.national}` : 'Mobile number',
phone: fixedExample.valid ? `e.g., ${fixedExample.number.national}` : 'Phone number',
international: mobileExample.valid ? `e.g., ${mobileExample.number.international}` : 'International format'
};
}
console.log(generateFormPlaceholders('US'));
// {
// mobile: "e.g., (201) 123-4567",
// phone: "e.g., (212) 123-4567",
// international: "e.g., +1 201-123-4567"
// }