CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-cleave-js

JavaScript library for formatting input text content when you are typing

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

phone-formatting.mddocs/

Phone Number Formatting

Complete API reference for international phone number formatting with support for 247 countries using Google's libphonenumber format patterns.

Capabilities

Phone Formatting Setup

Phone formatting requires country-specific addon files that provide Google's libphonenumber formatting patterns.

/**
 * Phone formatting requires external addon files
 * Each country requires its specific addon to be loaded
 */
interface PhoneFormattingSetup {
  // Required: Include country-specific addon before using
  // Format: cleave-phone.{countryCode}.js
  // Example: <script src="cleave-phone.us.js"></script>
  
  // Phone formatting options
  phone: true; // Enable phone formatting
  phoneRegionCode: string; // Two-letter country code
}

// Supported country codes (247 total)
type SupportedCountryCode = 
  | 'us' | 'uk' | 'au' | 'ca' | 'fr' | 'de' | 'jp' | 'cn' | 'in' | 'br'
  | 'mx' | 'it' | 'es' | 'ru' | 'kr' | 'th' | 'sg' | 'my' | 'ph' | 'id'
  | 'vn' | 'tw' | 'hk' | 'nz' | 'za' | 'ar' | 'cl' | 'co' | 'pe' | 've'
  // ... 217 more country codes
  ;

Basic Phone Formatting

Usage Examples:

<!-- Include required phone addon -->
<script src="cleave-phone.us.js"></script>
<script src="cleave.js"></script>
import Cleave from 'cleave.js';

// US phone formatting
const usPhone = new Cleave('#us-phone', {
  phone: true,
  phoneRegionCode: 'US'
});

// UK phone formatting (requires cleave-phone.gb.js)
const ukPhone = new Cleave('#uk-phone', {
  phone: true,
  phoneRegionCode: 'GB'
});

// Input: "1234567890"
// US Output: "(123) 456-7890"
// UK Output: "01234 567890" (format varies by UK number type)

Dynamic Region Switching

Changing phone region codes after initialization.

/**
 * Change phone region code dynamically
 * @param regionCode - Two-letter country code
 */
setPhoneRegionCode(regionCode: string): void;

Usage Examples:

const phoneInput = new Cleave('#phone', {
  phone: true,
  phoneRegionCode: 'US'
});

// Change to UK formatting (requires cleave-phone.gb.js to be loaded)
phoneInput.setPhoneRegionCode('GB');

// Change to Australian formatting (requires cleave-phone.au.js)
phoneInput.setPhoneRegionCode('AU');

React Phone Formatting

Using phone formatting with React components.

Usage Examples:

import React, { useState } from 'react';
import Cleave from 'cleave.js/react';

function PhoneForm() {
  const [country, setCountry] = useState('US');
  const [phoneNumber, setPhoneNumber] = useState('');

  return (
    <div>
      <select value={country} onChange={(e) => setCountry(e.target.value)}>
        <option value="US">United States</option>
        <option value="GB">United Kingdom</option>
        <option value="AU">Australia</option>
        <option value="CA">Canada</option>
        <option value="FR">France</option>
      </select>

      <Cleave
        value={phoneNumber}
        phone={true}
        phoneRegionCode={country}
        onChange={(e) => {
          setPhoneNumber(e.target.value);
          console.log('Raw phone:', e.target.rawValue);
        }}
        placeholder={`Enter ${country} phone number`}
      />
      
      <p>Formatted: {phoneNumber}</p>
    </div>
  );
}

Angular Phone Formatting

Using phone formatting with Angular directive.

Usage Examples:

<div ng-controller="PhoneController">
  <select ng-model="selectedCountry" ng-options="country.code as country.name for country in countries">
  </select>
  
  <input 
    ng-model="phoneNumber"
    cleave="getPhoneOptions()"
    placeholder="Phone number">
    
  <p>Raw: {{ phoneNumber }}</p>
</div>
angular.module('myApp').controller('PhoneController', function($scope) {
  $scope.selectedCountry = 'US';
  $scope.phoneNumber = '';
  
  $scope.countries = [
    { code: 'US', name: 'United States' },
    { code: 'GB', name: 'United Kingdom' },
    { code: 'AU', name: 'Australia' },
    { code: 'CA', name: 'Canada' }
  ];

  $scope.getPhoneOptions = function() {
    return {
      phone: true,
      phoneRegionCode: $scope.selectedCountry
    };
  };
});

Available Phone Addons

Complete list of available phone formatting addons with their file names and country codes.

/**
 * Phone addon files available (247 total)
 * Format: cleave-phone.{countryCode}.js
 */
interface PhoneAddons {
  // Major countries and regions
  'cleave-phone.us.js': 'US'; // United States
  'cleave-phone.gb.js': 'GB'; // United Kingdom
  'cleave-phone.au.js': 'AU'; // Australia
  'cleave-phone.ca.js': 'CA'; // Canada
  'cleave-phone.fr.js': 'FR'; // France
  'cleave-phone.de.js': 'DE'; // Germany
  'cleave-phone.jp.js': 'JP'; // Japan
  'cleave-phone.cn.js': 'CN'; // China
  'cleave-phone.in.js': 'IN'; // India
  'cleave-phone.br.js': 'BR'; // Brazil
  'cleave-phone.mx.js': 'MX'; // Mexico
  'cleave-phone.it.js': 'IT'; // Italy
  'cleave-phone.es.js': 'ES'; // Spain
  'cleave-phone.ru.js': 'RU'; // Russia
  'cleave-phone.kr.js': 'KR'; // South Korea
  
  // European countries
  'cleave-phone.at.js': 'AT'; // Austria
  'cleave-phone.be.js': 'BE'; // Belgium
  'cleave-phone.ch.js': 'CH'; // Switzerland
  'cleave-phone.dk.js': 'DK'; // Denmark
  'cleave-phone.fi.js': 'FI'; // Finland
  'cleave-phone.no.js': 'NO'; // Norway
  'cleave-phone.se.js': 'SE'; // Sweden
  'cleave-phone.nl.js': 'NL'; // Netherlands
  'cleave-phone.pl.js': 'PL'; // Poland
  'cleave-phone.pt.js': 'PT'; // Portugal
  
  // Asian countries
  'cleave-phone.th.js': 'TH'; // Thailand
  'cleave-phone.sg.js': 'SG'; // Singapore
  'cleave-phone.my.js': 'MY'; // Malaysia
  'cleave-phone.ph.js': 'PH'; // Philippines
  'cleave-phone.id.js': 'ID'; // Indonesia
  'cleave-phone.vn.js': 'VN'; // Vietnam
  'cleave-phone.tw.js': 'TW'; // Taiwan
  'cleave-phone.hk.js': 'HK'; // Hong Kong
  
  // Middle East and Africa
  'cleave-phone.ae.js': 'AE'; // UAE
  'cleave-phone.sa.js': 'SA'; // Saudi Arabia
  'cleave-phone.za.js': 'ZA'; // South Africa
  'cleave-phone.eg.js': 'EG'; // Egypt
  'cleave-phone.il.js': 'IL'; // Israel
  
  // Americas
  'cleave-phone.ar.js': 'AR'; // Argentina
  'cleave-phone.cl.js': 'CL'; // Chile
  'cleave-phone.co.js': 'CO'; // Colombia
  'cleave-phone.pe.js': 'PE'; // Peru
  'cleave-phone.ve.js': 'VE'; // Venezuela
  
  // And 192+ more countries...
}

Phone Formatting Examples by Country

Different countries have different phone number formats and patterns.

Usage Examples:

// United States: (123) 456-7890
const usPhone = new Cleave('#us', {
  phone: true,
  phoneRegionCode: 'US'
});

// United Kingdom: 020 7946 0958
const ukPhone = new Cleave('#uk', {
  phone: true,
  phoneRegionCode: 'GB'
});

// Australia: (02) 1234 5678
const auPhone = new Cleave('#au', {
  phone: true,
  phoneRegionCode: 'AU'
});

// France: 01 23 45 67 89
const frPhone = new Cleave('#fr', {
  phone: true,
  phoneRegionCode: 'FR'
});

// Germany: 030 12345678
const dePhone = new Cleave('#de', {
  phone: true,
  phoneRegionCode: 'DE'
});

// Japan: 03-1234-5678
const jpPhone = new Cleave('#jp', {
  phone: true,
  phoneRegionCode: 'JP'
});

// Brazil: (11) 91234-5678
const brPhone = new Cleave('#br', {
  phone: true,
  phoneRegionCode: 'BR'
});

// India: 9876 543 210
const inPhone = new Cleave('#in', {
  phone: true,
  phoneRegionCode: 'IN'
});

Phone Validation Integration

Combining phone formatting with validation logic.

Usage Examples:

function createValidatedPhoneInput(elementId, countryCode) {
  const phone = new Cleave(elementId, {
    phone: true,
    phoneRegionCode: countryCode,
    onValueChanged: function(e) {
      const rawValue = e.target.rawValue;
      const isValid = validatePhoneNumber(rawValue, countryCode);
      
      // Update UI based on validation
      const element = e.target;
      element.classList.toggle('valid', isValid);
      element.classList.toggle('invalid', !isValid);
      
      console.log(`Phone (${countryCode}):`, {
        formatted: e.target.value,
        raw: rawValue,
        valid: isValid
      });
    }
  });
  
  return phone;
}

function validatePhoneNumber(rawPhone, countryCode) {
  const validationRules = {
    'US': /^\d{10}$/,
    'GB': /^\d{10,11}$/,
    'AU': /^\d{9,10}$/,
    'FR': /^\d{10}$/,
    'DE': /^\d{10,12}$/
  };
  
  const rule = validationRules[countryCode];
  return rule ? rule.test(rawPhone) : rawPhone.length > 0;
}

// Usage
const validatedPhone = createValidatedPhoneInput('#phone', 'US');

Advanced Phone Configuration

Complex phone setups with multiple regions and dynamic switching.

Usage Examples:

class InternationalPhoneInput {
  constructor(inputId, selectId) {
    this.inputElement = document.querySelector(inputId);
    this.selectElement = document.querySelector(selectId);
    this.currentCleave = null;
    
    this.countries = [
      { code: 'US', name: 'United States', format: '(###) ###-####' },
      { code: 'GB', name: 'United Kingdom', format: '#### ### ####' },
      { code: 'AU', name: 'Australia', format: '(##) #### ####' },
      { code: 'FR', name: 'France', format: '## ## ## ## ##' },
      { code: 'DE', name: 'Germany', format: '### ########' }
    ];
    
    this.init();
  }
  
  init() {
    // Populate country select
    this.countries.forEach(country => {
      const option = document.createElement('option');
      option.value = country.code;
      option.textContent = `${country.name} (${country.format})`;
      this.selectElement.appendChild(option);
    });
    
    // Initialize with first country
    this.switchCountry(this.countries[0].code);
    
    // Handle country changes
    this.selectElement.addEventListener('change', (e) => {
      this.switchCountry(e.target.value);
    });
  }
  
  switchCountry(countryCode) {
    // Clean up existing instance
    if (this.currentCleave) {
      this.currentCleave.destroy();
    }
    
    // Create new instance for selected country
    this.currentCleave = new Cleave(this.inputElement, {
      phone: true,
      phoneRegionCode: countryCode,
      onValueChanged: (e) => {
        this.onPhoneChange(e, countryCode);
      }
    });
  }
  
  onPhoneChange(event, countryCode) {
    const country = this.countries.find(c => c.code === countryCode);
    console.log(`${country.name} phone:`, {
      formatted: event.target.value,
      raw: event.target.rawValue
    });
  }
  
  getValue() {
    return this.currentCleave ? this.currentCleave.getRawValue() : '';
  }
  
  getFormattedValue() {
    return this.currentCleave ? this.currentCleave.getFormattedValue() : '';
  }
}

// Usage
const phoneInput = new InternationalPhoneInput('#phone-input', '#country-select');

Error Handling

Handling cases where phone addons are not loaded.

Usage Examples:

function createPhoneInputSafe(elementId, countryCode) {
  try {
    const phone = new Cleave(elementId, {
      phone: true,
      phoneRegionCode: countryCode
    });
    
    console.log(`Phone input created for ${countryCode}`);
    return phone;
    
  } catch (error) {
    if (error.message.includes('Please include phone-type-formatter')) {
      console.error(`Phone addon not loaded for ${countryCode}`);
      console.error(`Please include: cleave-phone.${countryCode.toLowerCase()}.js`);
      
      // Fallback to basic formatting
      return new Cleave(elementId, {
        numericOnly: true,
        blocks: [3, 3, 4],
        delimiter: '-'
      });
    }
    
    throw error;
  }
}

// Usage with error handling
const safePhone = createPhoneInputSafe('#phone', 'US');

Install with Tessl CLI

npx tessl i tessl/npm-cleave-js

docs

angular-integration.md

index.md

phone-formatting.md

react-integration.md

vanilla-javascript.md

tile.json