Cleave.js

repository·master·Indexed 12 days ago

https://github.com/nosir/cleave.js

A JavaScript library for automatically formatting input text content—such as credit card numbers, phone numbers, dates, and numerals—as a user types to improve readability. Version 1.6.0. Note: This library is deprecated; users are encouraged to use cleave-zen for new projects.

Tokens
9K
Snippets
43
Records
47
Agent score
97%

What's inside Cleave.js

  1. How to bundle multiple countries for phone formatting

    master

    If your application needs to support multiple countries, do not include multiple individual country scripts (e.g., <script src="cleave-phone.ca.js"></script> and <script src="cleave-phone.us.js"></script>). This is inefficient.

    Instead, you should build a custom combination library (e.g., (US & CA).js) that contains only the required country metadata. To build your own combination, refer to the libphonenumber-country-metadata build guide.

  2. How to update the raw value in Cleave

    master

    The Cleave component is primarily an uncontrolled component. Do not attempt to bind the value attribute to a React state variable for data binding, as this can cause unexpected behavior.

    To programmatically update the input value, use the onInit pattern to get the Cleave instance and call cleave.setRawValue('...').

    // Correct way to update value:
    this.state.cleaveInstance.setRawValue('new-raw-value');
  3. Import Cleave.js React components and addons

    master

    Import the core React component from cleave.js/react. For phone formatting, import specific country addons.

    Important: When importing phone addons, the {country} code must be in lowercase (e.g., pt for Portugal), which differs from the phoneRegionCode option used in the component props.

    import React from 'react';
    import Cleave from 'cleave.js/react';
    import CleavePhone from 'cleave.js/dist/addons/cleave-phone.pt';
  4. Include the Cleave.js phone lib addon

    master

    To use phone number formatting, you must include the phone lib addon. Because the full international library is large, Cleave.js provides individual country addons (e.g., cleave-phone.au.js for Australia) to reduce bundle size. You can find country codes in the ISO 3166-1 alpha-2 list.

    Available options in dist/addons:

    • Individual country files: cleave-phone.{country}.js (approx. 14K minified).
    • All-in-one i18n file: cleave-phone.i18n.js (large size).
    • Custom libphonenumber instance: You can provide your own AsYouTypeFormatter to further reduce bundle size.
    // Example: Bringing your own libphonenumber instance
    const AsYouTypeFormatter = require('google-libphonenumber').AsYouTypeFormatter;
    window.Cleave = window.Cleave || {};
    window.Cleave.AsYouTypeFormatter = AsYouTypeFormatter;
  5. Use Cleave.js in ReactJS

    master

    Cleave.js provides a dedicated React component. You can use it like a standard <input/> element by passing an options prop and attaching event listeners like onChange and onFocus.

    When using onChange, the event object contains:

    • event.target.value: The formatted string.
    • event.target.rawValue: The unformatted (raw) string.
    import React from 'react'
    import ReactDOM from 'react-dom'
    import Cleave from 'cleave.js/react'
    
    class MyComponent extends React.Component {
      constructor(props, context) {
        super(props, context)
        this.onCreditCardChange = this.onCreditCardChange.bind(this)
        this.onCreditCardFocus = this.onCreditCardFocus.bind(this)
      }
    
      onCreditCardChange(event) {
        // formatted pretty value
        console.log(event.target.value)
    
        // raw value
        console.log(event.target.rawValue)
      }
    
      onCreditCardFocus(event) {
        // update some state
      }
    
      render() {
        return (
          <Cleave
            placeholder='Enter your credit card number'
            options={{ creditCard: true }}
            onFocus={this.onCreditCardFocus}
            onChange={this.onCreditCardChange}
          />
        )
      }
    }
  6. Import Cleave.js in CommonJS, AMD, and ES Modules

    master

    Cleave.js supports multiple module formats for integration into modern build pipelines.

    // CommonJS
    var Cleave = require('cleave.js');
    require('cleave.js/dist/addons/cleave-phone.{country}');
    var cleave = new Cleave(...);
    
    // AMD
    require(['cleave.js/dist/cleave.min', 'cleave.js/dist/addons/cleave-phone.{country}'], function (Cleave) {
        var cleave = new Cleave(...);
    });
    
    // ES Module (Rollup, Webpack)
    import Cleave from 'cleave.js';
    var cleave = new Cleave(...);
    
    // ES Module (Browser)
    import Cleave from 'node_modules/cleave.js/dist/cleave-esm.min.js';
    var cleave = new Cleave(...);
  7. Use Cleave.js globally in Vue.js

    master

    Since Cleave.js does not have official Vue.js support, you can register it as a global directive. This allows you to use the v-cleave directive on any input element throughout your application. The directive initializes a new Cleave instance when the element is inserted and synchronizes the formatted value back to the input during updates by dispatching an input event.

    import Vue from 'vue'
    import Cleave from 'cleave.js';
    
    Vue.directive('cleave', {
        inserted: (el, binding) => {
            el.cleave = new Cleave(el, binding.value || {})
        },
        update: (el) => {
            const event = new Event('input', {bubbles: true});
            setTimeout(function () {
                el.value = el.cleave.properties.result
                el.dispatchEvent(event)
            }, 100);
        }
    })
  8. Basic Usage with Vanilla JavaScript

    master

    To use Cleave.js in a standard web environment, include the script and then instantiate the Cleave class by passing a unique DOM element selector and an options object.

    Note: If you want to apply Cleave to multiple elements, you must create individual instances for each element (e.g., using a loop) rather than passing a single selector that matches multiple elements.

    <!-- 1. Include the script -->
    <script src="cleave.min.js"></script>
    
    <!-- 2. Create a text field -->
    <input class="input-phone" type="text" />
    
    <script>
    // 3. Initialize Cleave
    var cleave = new Cleave('.input-phone', {
      phone: true,
      phoneRegionCode: '{country}',
    })
    </script>
  9. How to call Cleave public methods using onInit

    master

    To access Cleave's public methods (like setRawValue), you must capture the Cleave instance using the onInit callback. Store this instance in your component's state or a variable.

    // 1. Define the init handler
    onCreditCardInit(cleave) {
        this.setState({creditCardCleave: cleave});
    }
    
    // 2. Pass it to the component
    <Cleave options={{creditCard: true}} onInit={this.onCreditCardInit} />
    
    // 3. Use the instance later
    this.state.creditCardCleave.setRawValue('123456789');
  10. How to call Cleave.js public methods in AngularJS

    master

    To access the Cleave instance and call its public methods (like getISOFormatDate()), use the onInit callback option. The directive passes the Cleave instance as a parameter to this callback. You can then store this instance on your $scope to use it elsewhere in your controller.

    // In your controller
    $scope.onInit = function(cleave) {
        $scope.model.cleave = cleave;
    };
    
    $scope.options = {
        onInit: $scope.onInit
    };
    <input ng-model="model.rawValue" type="text" cleave="options" />