cleave.js - Documentation

Introduction

What is Cleave.js?

Cleave.js is a lightweight, versatile JavaScript library that formats input fields as you type. It’s designed to simplify the process of creating user-friendly input forms for various data types, such as credit cards, phone numbers, dates, and more. Cleave.js handles the formatting automatically, ensuring data integrity and improving the user experience by providing immediate visual feedback. It operates directly on the input element, without relying on complex frameworks or significant DOM manipulation.

Why use Cleave.js?

Installation

Cleave.js can be easily installed via several methods:

<script src="https://cdn.jsdelivr.net/npm/cleave.js@1.6.0/dist/cleave.min.js"></script>
npm install cleave.js

Then, import it into your JavaScript file:

import Cleave from 'cleave.js';
yarn add cleave.js

Then, import it into your JavaScript file:

import Cleave from 'cleave.js';

Basic Usage

The core of using Cleave.js involves selecting an input element and initializing a Cleave instance. Here’s a simple example formatting a phone number:

<input type="tel" id="phone" placeholder="Phone Number">
const cleave = new Cleave('#phone', {
  phone: true,
});

This code snippet selects the input element with the ID “phone” and initializes Cleave with the phone: true option, which automatically formats the input as a phone number. Other options allow for various formats (credit cards, dates, etc.) and customization of delimiters and other aspects. Refer to the advanced documentation for further options and configurations.

Core Features

Number Formatting

Cleave.js provides robust number formatting capabilities. You can easily format numbers with thousands separators, decimal points, and control the number of decimal places. This is achieved using the numeral option.

Basic Usage:

new Cleave('.numeric-input', {
  numeral: true,
  numeralDecimalScale: 2, // Optional: Set the number of decimal places
});

This will format the number with thousands separators and two decimal places. Leaving out numeralDecimalScale will allow for a variable number of decimal places.

Currency Formatting

Cleave.js simplifies currency formatting by combining number formatting with currency symbols. The numeral, numeralThousandsGroupStyle, and prefix options are key for this functionality.

Example:

new Cleave('.currency-input', {
  numeral: true,
  numeralThousandsGroupStyle: 'thousand',
  prefix: '$',
});

This will format the input as a USD currency value with thousands separators. You can adjust the prefix for other currencies (e.g., ‘€’, ‘£’). Consider using a dedicated currency library for more advanced currency formatting needs.

Credit Card Formatting

Cleave.js efficiently handles credit card formatting, automatically adding spaces between groups of numbers based on the card type. The creditCard option activates this feature.

Example:

new Cleave('.credit-card-input', {
  creditCard: true
});

This will automatically detect the credit card type based on the input and format accordingly. Note that Cleave.js itself doesn’t perform credit card validation; you should use a dedicated library for this purpose.

Date Formatting

Cleave.js offers date formatting with various date formats supported through the date option and its associated sub-options like datePattern.

Example (MM/DD/YYYY):

new Cleave('.date-input', {
    date: true,
    datePattern: ['m', 'd', 'Y']
});

You can customize the datePattern array to define different date formats. Consult the documentation for all available date pattern characters. Remember to handle date validation separately for robust date input.

Custom Delimiters

Cleave.js allows you to customize delimiters for various parts of the formatted output. This includes thousands separators, decimal points, and other custom delimiters using options like delimiter, decimalPoint, and block, amongst others.

Example:

new Cleave('.custom-input', {
  numeral: true,
  delimiter: '.',
  decimalPoint: ',',
  numeralThousandsGroupStyle: 'thousand'
});

This example utilizes a period (.) as the thousands separator and a comma (,) as the decimal point, which is common in some European locales. Adjust the options to suit your specific requirements. Remember to always check for delimiter conflicts to avoid unexpected behavior.

Options and Customization

Delimiter

The delimiter option specifies the character used to separate blocks of digits. The default is a space. For example:

new Cleave('.my-input', {
  delimiter: '-',
});

This will use a hyphen (-) as the delimiter.

Blocks

The blocks option is an array defining the lengths of each block separated by the delimiter. For example, to create a format like XXX-XXX-XXX, use:

new Cleave('.my-input', {
  blocks: [3, 3, 3],
  delimiter: '-',
});

Prefix

The prefix option adds a prefix string to the beginning of the input value.

new Cleave('.my-input', {
  prefix: '+1 ',
});

Suffix

The suffix option adds a suffix string to the end of the input value.

new Cleave('.my-input', {
  suffix: ' km',
});

Numeric Only

The numericOnly option (boolean) restricts input to only numeric characters (0-9). Defaults to false.

new Cleave('.my-input', {
  numericOnly: true,
});

Decimal

The decimal option (boolean) allows for a decimal point. Defaults to false. Use in conjunction with other options for full numeric formatting (see numeral).

new Cleave('.my-input', {
  numeral: true,
  decimal: true,
  delimiter: ',',
  decimalPoint: '.'
});

Thousands Separator

The thousandsSeparator option defines the thousands separator character. (See also numeralThousandsGroupStyle for controlling grouping style.) This option is typically used with numeric formatting.

Auto Decimals

The numeralDecimalScale option (numeric) automatically sets the number of decimal places after the decimal point when the numeral option is used.

Strip

The strip option (boolean) determines whether non-numeric characters should be stripped from the input value before formatting. Defaults to true.

Root

The root option allows specifying a different element to append the Cleave instance to. Useful for scenarios other than directly attaching to the input element.

Disable Phone Region Code

The phoneRegionCode option can be set to false to disable the automatic addition of country codes when using phone number formatting.

Combine Credit Card

The combineCreditCards option combines multiple credit card numbers into a single input.

Credit Card Placeholder

The creditCardPlaceholder option allows defining a custom placeholder for credit card input.

Use Credit Card Placeholder

The useCreditPlaceholder option (boolean) enables or disables the default credit card placeholder.

Time

The time option (boolean) enables time formatting. Further options control specific time formatting patterns (not detailed here, consult the documentation).

Date

The date option (boolean) enables date formatting. datePattern allows customizing the date format (e.g., ‘YYYY-MM-DD’, ‘MM/DD/YYYY’).

Uppercase

The uppercase option (boolean) converts the input to uppercase.

Lowercase

The lowercase option (boolean) converts the input to lowercase.

MaxLength

The maxLength option limits the maximum length of the input value.

OnValueChanged

The onValueChanged callback function is triggered whenever the formatted value changes.

OnInput

The onInput callback function is triggered when the input event occurs.

OnKeyDown

The onKeyDown callback function is triggered when a key is pressed down.

OnKeyUp

The onKeyUp callback function is triggered when a key is released.

BeforePaste

The beforePaste callback function is triggered before the paste event. It is passed the pasted content and can be used to sanitize it before formatting.

AfterPaste

The afterPaste callback function is triggered after a paste event has occurred and the input has been processed.

Advanced Usage

Custom Formatting

Beyond the built-in formats, Cleave.js allows for highly customized formatting using the blocks and delimiter options in conjunction with other properties. You can create virtually any format by carefully defining the structure of the input.

For example, to create a format like “AAA-BBB-CCCC-DDDD”, you would use:

new Cleave('.my-input', {
    blocks: [3, 3, 4, 4],
    delimiter: '-',
});

Remember to handle input validation separately as Cleave.js primarily focuses on formatting, not data validation.

Integrating with Frameworks (React, Angular, Vue)

Cleave.js is framework-agnostic, meaning it can be readily integrated into various JavaScript frameworks. The basic integration involves importing Cleave.js and using it within the component’s lifecycle methods.

React:

import React, { useRef, useEffect } from 'react';
import Cleave from 'cleave.js';

function MyComponent() {
  const inputRef = useRef(null);

  useEffect(() => {
    const cleave = new Cleave(inputRef.current, {
      // Cleave options here
    });
    return () => cleave.destroy(); // Cleanup on unmount
  }, []);

  return (
    <input type="text" ref={inputRef} />
  );
}

Angular: You would typically use Cleave.js within an Angular component’s ngOnInit lifecycle hook, ensuring the Cleave instance is initialized after the component’s view is initialized. Remember to handle the destruction of the Cleave instance in ngOnDestroy.

Vue: In Vue, you would use a mounted lifecycle hook to initialize Cleave.js and a beforeDestroy hook to destroy it. You might use a ref to access the input element.

In all frameworks, remember to clean up the Cleave instance (using destroy()) to prevent memory leaks when the component unmounts or is destroyed.

Handling Events

Cleave.js provides several events (callbacks) that you can use to react to changes in the input value. These include onValueChanged, onInput, onKeyDown, onKeyUp, beforePaste, and afterPaste. You can leverage these events to perform actions based on user interaction, such as updating other parts of the UI, performing real-time validation, or making API calls.

For example, using onValueChanged:

new Cleave('.my-input', {
  // ... other options ...
  onValueChanged: function(e) {
    console.log("Value changed:", e.value);
    // Perform actions based on the updated value
  }
});

Internationalization

For internationalization (i18n), you’ll need to manually adjust options such as delimiter, decimalPoint, thousandsSeparator, and datePattern according to the locale. Cleave.js itself doesn’t have built-in internationalization features; you are responsible for providing the correct locale-specific formatting parameters. You might consider integrating with a dedicated i18n library to manage locale-specific data.

Accessibility

Ensure accessibility by providing appropriate ARIA attributes to the input element. For example, include aria-label or aria-labelledby to describe the purpose of the input, aria-describedby to link to any error messages or instructions, and aria-invalid to indicate if the input value is invalid. Use clear and concise labels for input fields. Adhere to general accessibility best practices for your chosen framework. Consider providing alternative input methods for users with disabilities, such as keyboard navigation and screen reader compatibility.

Examples

Basic Number Formatting

This example demonstrates basic number formatting with thousands separators and two decimal places:

<input type="text" id="basicNumber">
new Cleave('#basicNumber', {
  numeral: true,
  numeralDecimalScale: 2,
});

This will format numbers like this: 1,234,567.89

Currency Formatting Example

This example shows currency formatting with a dollar sign prefix and thousands separators:

<input type="text" id="currency">
new Cleave('#currency', {
  numeral: true,
  prefix: '$',
  numeralThousandsGroupStyle: 'thousand'
});

This will format numbers like this: $1,234,567.89

Credit Card Formatting Example

This example demonstrates basic credit card formatting:

<input type="text" id="creditCard">
new Cleave('#creditCard', {
  creditCard: true
});

This will automatically format the input as a credit card number, adding spaces between groups of numbers as the user types.

Date Formatting Example

This example shows date formatting in MM/DD/YYYY format:

<input type="text" id="date">
new Cleave('#date', {
  date: true,
  datePattern: ['m', 'd', 'Y']
});

This will format the input as a date in MM/DD/YYYY format.

Custom Formatting Example

This example demonstrates creating a custom format using the blocks and delimiter options. This example creates a format like AAA-BBB-CCCC:

<input type="text" id="custom">
new Cleave('#custom', {
  blocks: [3, 3, 4],
  delimiter: '-',
});

This will format the input with three groups of digits separated by hyphens. Remember that this only formats the input; you’ll need additional validation to ensure the data entered conforms to your requirements.

Troubleshooting

Common Issues and Solutions

Debugging Tips

API Reference

Constructor Options

The Cleave.js constructor accepts a wide range of options to customize its behavior. Here are some of the key options:

This is not an exhaustive list; refer to the complete documentation for a comprehensive list of options.

Methods

Events

Cleave.js provides several events that you can listen for to react to changes and user interactions:

These events are specified as options in the Cleave constructor. Each event option should be a function that will be executed when the corresponding event occurs.