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.
Simplified Form Development: Cleave.js significantly reduces the amount of code needed to create formatted input fields. You avoid the complexity of manual formatting and validation.
Improved User Experience: Real-time formatting provides immediate visual feedback to users, reducing errors and making data entry more intuitive.
Enhanced Data Integrity: By enforcing specific formatting rules, Cleave.js helps to ensure that the data entered is in the correct format, minimizing the need for server-side validation.
Lightweight and Fast: Cleave.js is designed to be small and efficient, minimizing the impact on your application’s performance. It doesn’t require large dependencies.
Customizable: It offers extensive customization options, allowing you to tailor the formatting to your specific needs.
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';
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.
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.
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.
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.
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.
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.
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.
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: '-',
; })
The prefix
option adds a prefix string to the beginning of the input value.
new Cleave('.my-input', {
prefix: '+1 ',
; })
The suffix
option adds a suffix string to the end of the input value.
new Cleave('.my-input', {
suffix: ' km',
; })
The numericOnly
option (boolean) restricts input to only numeric characters (0-9). Defaults to false
.
new Cleave('.my-input', {
numericOnly: true,
; })
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: '.'
; })
The thousandsSeparator
option defines the thousands separator character. (See also numeralThousandsGroupStyle
for controlling grouping style.) This option is typically used with numeric formatting.
The numeralDecimalScale
option (numeric) automatically sets the number of decimal places after the decimal point when the numeral
option is used.
The strip
option (boolean) determines whether non-numeric characters should be stripped from the input value before formatting. Defaults to true
.
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.
The phoneRegionCode
option can be set to false
to disable the automatic addition of country codes when using phone number formatting.
The combineCreditCards
option combines multiple credit card numbers into a single input.
The creditCardPlaceholder
option allows defining a custom placeholder for credit card input.
The useCreditPlaceholder
option (boolean) enables or disables the default credit card placeholder.
The time
option (boolean) enables time formatting. Further options control specific time formatting patterns (not detailed here, consult the documentation).
The date
option (boolean) enables date formatting. datePattern
allows customizing the date format (e.g., ‘YYYY-MM-DD’, ‘MM/DD/YYYY’).
The uppercase
option (boolean) converts the input to uppercase.
The lowercase
option (boolean) converts the input to lowercase.
The maxLength
option limits the maximum length of the input value.
The onValueChanged
callback function is triggered whenever the formatted value changes.
The onInput
callback function is triggered when the input event occurs.
The onKeyDown
callback function is triggered when a key is pressed down.
The onKeyUp
callback function is triggered when a key is released.
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.
The afterPaste
callback function is triggered after a paste event has occurred and the input has been processed.
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.
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.
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
}; })
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.
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.
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
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
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.
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.
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.
Incorrect Formatting: Double-check your Cleave.js options. Ensure that the options you’ve provided (e.g., blocks
, delimiter
, prefix
, suffix
, datePattern
, etc.) accurately reflect your desired format. Incorrect or conflicting options are a frequent source of formatting problems. Carefully review the documentation for each option’s purpose and usage.
No Formatting at All: Verify that Cleave.js is correctly included in your project and that the initialization code is executed after the DOM element is ready. Inspect your browser’s developer console for any JavaScript errors that may be preventing Cleave.js from functioning. Make sure the selector you are using (#myInput
, .myClass
, etc.) correctly targets the input element.
Unexpected Behavior with Specific Characters: If you encounter unexpected behavior with certain characters, ensure that your input field’s type
attribute is appropriately set (e.g., text
, tel
, number
). Some input types might have built-in browser behavior that interferes with Cleave.js’s formatting. The strip
option can be used to control character stripping behavior.
Memory Leaks: Always remember to call the destroy()
method on your Cleave instance when the component or element is no longer needed (especially in frameworks like React, Angular, or Vue). This is crucial to prevent memory leaks, particularly in applications with dynamically added or removed input fields.
Conflicting JavaScript Libraries: Ensure there are no conflicts with other JavaScript libraries that might be manipulating the same DOM elements or interfering with event handling. Test by temporarily disabling other libraries to isolate the issue.
Browser Developer Console: Use your browser’s developer console to check for JavaScript errors and warnings. This can quickly pinpoint problems in your code or conflicts with other scripts.
Inspect the Cleave Instance: After initializing Cleave.js, you can inspect the Cleave instance using your browser’s developer tools to see its properties and current state. This can help identify if Cleave.js is correctly initialized and if the options are being applied as expected.
Simplify Your Code: If you’re encountering complex issues, try simplifying your Cleave.js configuration to isolate the problematic option or combination of options. A minimal, reproducible example helps to identify the root cause.
Check for Updates: Make sure you’re using the latest version of Cleave.js. Updates often include bug fixes and improvements.
Read the Documentation: The official Cleave.js documentation provides detailed explanations of the options and their usage. Carefully review this documentation to ensure you are using the options correctly.
Search for Existing Issues: Check the Cleave.js issue tracker or online forums. Someone might have encountered and solved a similar problem.
The Cleave.js constructor accepts a wide range of options to customize its behavior. Here are some of the key options:
element
(required): A CSS selector string or DOM element representing the input field to be formatted.
blocks
(optional): An array of numbers defining the lengths of blocks separated by the delimiter. Example: [3, 3, 3]
for a three-part format like XXX-XXX-XXX.
delimiter
(optional): The character used to separate blocks. Defaults to a space.
prefix
(optional): A string to prepend to the input value.
suffix
(optional): A string to append to the input value.
numericOnly
(optional): Boolean indicating whether only numeric characters are allowed. Defaults to false
.
creditCard
(optional): Boolean indicating credit card formatting. Defaults to false
.
date
(optional): Boolean indicating date formatting. Requires datePattern
if true. Defaults to false
.
datePattern
(optional): An array defining the date format pattern (e.g., ['Y', 'm', 'd']
for YYYY-MM-DD).
time
(optional): Boolean indicating time formatting. Defaults to false
.
timePattern
(optional): String specifying the time format (e.g., ‘H:m:s’).
phone
(optional): Boolean indicating phone number formatting (requires phoneRegionCode
if true). Defaults to false
.
phoneRegionCode
(optional): String specifying the country code for phone number formatting.
numeral
(optional): Boolean enabling numeral formatting (with thousands separators and decimal places). Defaults to false
.
numeralDecimalScale
(optional): Number of decimal places for numeral formatting.
numeralThousandsGroupStyle
(optional): Style of thousands grouping (‘thousand’ or ‘lakh’).
strip
(optional): Boolean to control whether non-numeric characters are stripped before formatting. Defaults to true
.
maxLength
(optional): Maximum length of the input value.
onValueChanged
(optional): A callback function triggered when the formatted value changes.
onInput
(optional): A callback function triggered on the input event.
onKeyDown
(optional): A callback function triggered on the keydown event.
onKeyUp
(optional): A callback function triggered on the keyup event.
beforePaste
(optional): A callback function triggered before the paste event.
afterPaste
(optional): A callback function triggered after the paste event.
root
(optional): Alternative element to append the Cleave instance to (beyond the direct input element).
This is not an exhaustive list; refer to the complete documentation for a comprehensive list of options.
setRawValue(value)
: Sets the raw (unformatted) value of the input field.
getValue()
: Returns the formatted value of the input field.
getRawValue()
: Returns the raw (unformatted) value of the input field.
destroy()
: Removes the Cleave.js instance from the DOM element, releasing resources. Crucial to prevent memory leaks.
Cleave.js provides several events that you can listen for to react to changes and user interactions:
onValueChanged
: Triggered whenever the formatted value changes. The callback receives an object with a value
property containing the formatted value.
onInput
: Triggered when the input event occurs.
onKeyDown
: Triggered when a key is pressed down.
onKeyUp
: Triggered when a key is released.
beforePaste
: Triggered before a paste event occurs; allowing pre-processing of pasted data.
afterPaste
: Triggered after a paste event completes.
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.