CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-phone-number-input

Telephone number input React component with country selection, validation, and formatting capabilities

Pending
Overview
Eval results
Files

utility-functions.mddocs/

Utility Functions

Comprehensive phone number parsing, formatting, and validation utilities powered by libphonenumber-js. These functions provide the core phone number processing capabilities used throughout the component library and are available for standalone use.

Capabilities

Phone Number Formatting

Functions for formatting phone numbers in different display formats.

/**
 * Format phone number in national format for display
 * @param value - Phone number in E.164 format or string
 * @returns Formatted phone number for national display (e.g., "(213) 373-4253")
 */
function formatPhoneNumber(value: string): string;

/**
 * Format phone number in international format for display
 * @param value - Phone number in E.164 format or string  
 * @returns Formatted phone number for international display (e.g., "+1 213 373 4253")
 */
function formatPhoneNumberIntl(value: string): string;

Usage Examples:

import { formatPhoneNumber, formatPhoneNumberIntl } from "react-phone-number-input";

// Format for national display
const nationalFormat = formatPhoneNumber("+12133734253");
console.log(nationalFormat); // "(213) 373-4253"

// Format for international display  
const intlFormat = formatPhoneNumberIntl("+12133734253"); 
console.log(intlFormat); // "+1 213 373 4253"

// Handle undefined/invalid values
const invalidFormat = formatPhoneNumber("");
console.log(invalidFormat); // "" (empty string)

const undefinedFormat = formatPhoneNumber(undefined);
console.log(undefinedFormat); // "" (empty string)

Core Variant Formatting

Core variants require manual metadata parameter for smaller bundle sizes.

/**
 * Format phone number in national format (core version)
 * @param value - Phone number in E.164 format or string
 * @param metadata - libphonenumber-js metadata object
 * @returns Formatted phone number for national display
 */
function formatPhoneNumber(value: string, metadata: Metadata): string;

/**
 * Format phone number in international format (core version)  
 * @param value - Phone number in E.164 format or string
 * @param metadata - libphonenumber-js metadata object
 * @returns Formatted phone number for international display
 */
function formatPhoneNumberIntl(value: string, metadata: Metadata): string;

Core Usage Example:

import { formatPhoneNumber, formatPhoneNumberIntl } from "react-phone-number-input/core";
import metadata from "libphonenumber-js/metadata.json";

const nationalFormat = formatPhoneNumber("+12133734253", metadata);
const intlFormat = formatPhoneNumberIntl("+12133734253", metadata);

Phone Number Parsing

Parse and extract information from phone number strings.

/**
 * Parse phone number string into PhoneNumber object
 * @param input - Phone number string in any format
 * @param defaultCountry - Default country for national numbers (optional)
 * @returns PhoneNumber object or undefined if invalid
 */
function parsePhoneNumber(input: string, defaultCountry?: Country): PhoneNumber | undefined;

/**
 * PhoneNumber class with parsed phone number information
 */
declare class PhoneNumber {
  /** Country code (e.g., "US") */
  country?: Country;
  /** Country calling code (e.g., "1") */
  countryCallingCode: string;
  /** National number without country code */
  nationalNumber: string;
  /** Full number in E.164 format */
  number: string;
  /** Check if number is possible */
  isPossible(): boolean;
  /** Check if number is valid */
  isValid(): boolean;
  /** Format number in specified format */
  format(format: 'E164' | 'INTERNATIONAL' | 'NATIONAL' | 'RFC3966'): string;
  /** Get formatted number for URI (tel: links) */
  getURI(): string;
  /** Get possible countries for this number */
  getPossibleCountries(): Country[];
}

Parsing Examples:

import { parsePhoneNumber } from "react-phone-number-input";

// Parse international number
const parsed1 = parsePhoneNumber("+12133734253");
console.log(parsed1?.country); // "US"
console.log(parsed1?.nationalNumber); // "2133734253"
console.log(parsed1?.number); // "+12133734253"

// Parse national number with default country
const parsed2 = parsePhoneNumber("(213) 373-4253", "US");
console.log(parsed2?.number); // "+12133734253"

// Handle invalid numbers
const parsed3 = parsePhoneNumber("invalid");
console.log(parsed3); // undefined

// Check validity
const phoneNumber = parsePhoneNumber("+12133734253");
if (phoneNumber) {
  console.log(phoneNumber.isValid()); // true
  console.log(phoneNumber.isPossible()); // true
  console.log(phoneNumber.format('NATIONAL')); // "(213) 373-4253"
  console.log(phoneNumber.format('INTERNATIONAL')); // "+1 213 373 4253"
}

Phone Number Validation

Functions for validating phone number correctness.

/**
 * Check if phone number is valid
 * @param input - Phone number string in any format
 * @param defaultCountry - Default country for national numbers (optional)
 * @returns true if phone number is valid, false otherwise
 */
function isValidPhoneNumber(input: string, defaultCountry?: Country): boolean;

/**
 * Check if phone number is possible (less strict than valid)
 * @param input - Phone number string in any format
 * @param defaultCountry - Default country for national numbers (optional)
 * @returns true if phone number format is possible, false otherwise
 */
function isPossiblePhoneNumber(input: string, defaultCountry?: Country): boolean;

Validation Examples:

import { isValidPhoneNumber, isPossiblePhoneNumber } from "react-phone-number-input";

// Validate international numbers
console.log(isValidPhoneNumber("+12133734253")); // true
console.log(isValidPhoneNumber("+1213373425")); // false (too short)

// Validate national numbers with default country
console.log(isValidPhoneNumber("(213) 373-4253", "US")); // true
console.log(isValidPhoneNumber("213-373-4253", "US")); // true

// Check if number format is possible
console.log(isPossiblePhoneNumber("+19999999999")); // true (possible format)
console.log(isPossiblePhoneNumber("123")); // false (too short)

// Validation in form handling
function validatePhoneNumber(value: string): string | boolean {
  if (!value) return "Phone number is required";
  if (!isValidPhoneNumber(value)) return "Please enter a valid phone number";
  return true;
}

Country Information Functions

Functions for working with country codes and calling codes.

/**
 * Get list of all supported country codes
 * @returns Array of two-letter country codes
 */
function getCountries(): Country[];

/**
 * Get country calling code for a country
 * @param country - Two-letter country code
 * @returns Country calling code as string
 */
function getCountryCallingCode(country: Country): string;

/**
 * Check if country is supported by the library
 * @param country - Two-letter country code to check
 * @returns true if country is supported, false otherwise
 */
function isSupportedCountry(country: Country): boolean;

Country Functions Examples:

import { 
  getCountries, 
  getCountryCallingCode, 
  isSupportedCountry 
} from "react-phone-number-input";

// Get all supported countries
const countries = getCountries();
console.log(countries); // ["AD", "AE", "AF", "AG", ...]
console.log(countries.length); // ~250 countries

// Get calling codes
console.log(getCountryCallingCode("US")); // "1"
console.log(getCountryCallingCode("GB")); // "44"
console.log(getCountryCallingCode("DE")); // "49"

// Check country support
console.log(isSupportedCountry("US")); // true
console.log(isSupportedCountry("XX")); // false

// Build custom country selector
function buildCountryOptions(labels: Record<string, string>) {
  return getCountries().map(country => ({
    value: country,
    label: `${labels[country]} +${getCountryCallingCode(country)}`,
    supported: isSupportedCountry(country)
  }));
}

Error Handling

Utility functions handle various error conditions gracefully.

// Error handling patterns for utility functions

// Formatting functions return empty string for invalid input
formatPhoneNumber("") // returns ""
formatPhoneNumber(null) // returns ""
formatPhoneNumber(undefined) // returns ""

// Parsing returns undefined for invalid input
parsePhoneNumber("invalid") // returns undefined
parsePhoneNumber("") // returns undefined

// Validation returns false for invalid input
isValidPhoneNumber("") // returns false
isValidPhoneNumber("invalid") // returns false

// Country functions handle invalid input
getCountryCallingCode("XX") // throws error for unsupported country
isSupportedCountry("XX") // returns false (safe check)

Safe Error Handling Examples:

// Safe formatting with fallbacks
function safeFormatPhoneNumber(value: string): string {
  try {
    return formatPhoneNumber(value) || value;
  } catch (error) {
    return value; // Return original value if formatting fails
  }
}

// Safe parsing with validation
function safeParsePhoneNumber(input: string, defaultCountry?: Country) {
  if (!input || typeof input !== 'string') return undefined;
  
  try {
    return parsePhoneNumber(input, defaultCountry);
  } catch (error) {
    console.warn('Phone number parsing failed:', error);
    return undefined;
  }
}

// Safe country code lookup
function safeGetCountryCallingCode(country: Country): string | undefined {
  if (!isSupportedCountry(country)) return undefined;
  
  try {
    return getCountryCallingCode(country);
  } catch (error) {
    return undefined;
  }
}

Custom Country Selection

Utility functions enable building custom country selection components.

// Helper types for custom country selection
type CountryOption = {
  value: Country;
  label: string;
  callingCode: string;
};

// Build country options with calling codes
function buildCountryOptions(labels: Record<Country, string>): CountryOption[] {
  return getCountries()
    .filter(country => isSupportedCountry(country))
    .map(country => ({
      value: country,
      label: labels[country] || country,
      callingCode: getCountryCallingCode(country)
    }))
    .sort((a, b) => a.label.localeCompare(b.label));
}

Custom Country Select Example:

import React from "react";
import { getCountries, getCountryCallingCode } from "react-phone-number-input";
import en from "react-phone-number-input/locale/en.json";

function CustomCountrySelect({ value, onChange, ...rest }) {
  const countries = getCountries();
  
  return (
    <select
      {...rest}
      value={value || ""}
      onChange={e => onChange(e.target.value || undefined)}
    >
      <option value="">{en.ZZ}</option>
      {countries.map(country => (
        <option key={country} value={country}>
          {en[country]} +{getCountryCallingCode(country)}
        </option>
      ))}
    </select>
  );
}

Install with Tessl CLI

npx tessl i tessl/npm-react-phone-number-input

docs

customization.md

framework-integrations.md

index.md

input-components.md

internationalization.md

phone-input-components.md

utility-functions.md

tile.json