JavaScript library for formatting input text content when you are typing
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Complete API reference for using Cleave.js in vanilla JavaScript applications with detailed configuration options and instance methods.
Creates a new Cleave instance for formatting input elements.
/**
* Construct a new Cleave instance by passing the configuration object
* @param element - CSS selector string, HTMLElement, or NodeList
* @param options - Configuration options object
*/
constructor Cleave(element: string | HTMLElement | NodeList, options: CleaveOptions);Usage Examples:
import Cleave from 'cleave.js';
// Using CSS selector
const cleave1 = new Cleave('#input-id', { creditCard: true });
// Using HTMLElement
const element = document.getElementById('input-id');
const cleave2 = new Cleave(element, { phone: true, phoneRegionCode: 'US' });
// Using NodeList (uses first element)
const elements = document.querySelectorAll('.cleave-input');
const cleave3 = new Cleave(elements, { numeral: true });Get and set input values in both formatted and raw forms.
/**
* Set the raw unformatted value
* @param value - Raw value to set
*/
setRawValue(value: string): void;
/**
* Get the raw unformatted value
* @returns Raw value without formatting
*/
getRawValue(): string;
/**
* Get the current formatted display value
* @returns Formatted value as displayed in input
*/
getFormattedValue(): string;Usage Examples:
const cleave = new Cleave('#input', { creditCard: true });
// Set raw value (will be automatically formatted)
cleave.setRawValue('4111111111111111');
// Get values
console.log(cleave.getRawValue()); // "4111111111111111"
console.log(cleave.getFormattedValue()); // "4111 1111 1111 1111"Specialized methods for date and time formatted inputs.
/**
* Get ISO format date string (date mode only)
* @returns ISO date string or empty string if not in date mode
*/
getISOFormatDate(): string;
/**
* Get ISO format time string (time mode only)
* @returns ISO time string or empty string if not in time mode
*/
getISOFormatTime(): string;Usage Examples:
// Date formatting
const dateInput = new Cleave('#date', {
date: true,
datePattern: ['d', 'm', 'Y']
});
dateInput.setRawValue('25/12/2023');
console.log(dateInput.getISOFormatDate()); // "2023-12-25"
// Time formatting
const timeInput = new Cleave('#time', {
time: true,
timePattern: ['h', 'm', 's'],
timeFormat: '24'
});
timeInput.setRawValue('14:30:45');
console.log(timeInput.getISOFormatTime()); // "14:30:45"Methods specific to phone number formatting.
/**
* Change the phone region code after initialization
* @param regionCode - Two-letter country code
*/
setPhoneRegionCode(regionCode: string): void;Usage Examples:
// Requires phone addon: <script src="cleave-phone.us.js"></script>
const phoneInput = new Cleave('#phone', {
phone: true,
phoneRegionCode: 'US'
});
// Change region dynamically
phoneInput.setPhoneRegionCode('UK');Instance lifecycle and cleanup methods.
/**
* Remove event listeners and cleanup instance
*/
destroy(): void;
/**
* String representation of the instance
* @returns "[Cleave Object]"
*/
toString(): string;Usage Examples:
const cleave = new Cleave('#input', { creditCard: true });
// Clean up when done
cleave.destroy();
// String representation
console.log(cleave.toString()); // "[Cleave Object]"Automatic credit card number formatting with type detection.
interface CreditCardOptions {
creditCard: boolean; // Enable credit card formatting
creditCardStrictMode?: boolean; // Enable strict validation (default: false)
onCreditCardTypeChanged?: (type: CreditCardType) => void; // Type change callback
}
type CreditCardType = 'amex' | 'visa' | 'mastercard' | 'discover' | 'jcb' | 'dankort' | 'instapayment' | 'uatp' | 'mir' | 'unionPay' | 'general';Usage Examples:
const creditCard = new Cleave('#cc', {
creditCard: true,
creditCardStrictMode: true,
onCreditCardTypeChanged: function (type) {
console.log('Detected card type:', type);
// Update UI based on card type
document.getElementById('card-icon').className = `card-${type}`;
}
});International phone number formatting with country-specific patterns.
interface PhoneOptions {
phone: boolean; // Enable phone formatting
phoneRegionCode?: string; // Country code (default: 'AU')
}Usage Examples:
// US phone formatting (requires cleave-phone.us.js)
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'
});Date input formatting with validation and constraints.
interface DateOptions {
date: boolean; // Enable date formatting
datePattern?: string[]; // Date pattern tokens (default: ['d', 'm', 'Y'])
dateMin?: string; // Minimum date constraint (YYYY-MM-DD format)
dateMax?: string; // Maximum date constraint (YYYY-MM-DD format)
}Usage Examples:
const dateInput = new Cleave('#date', {
date: true,
datePattern: ['m', 'd', 'Y'], // US format: MM/DD/YYYY
dateMin: '2020-01-01',
dateMax: '2030-12-31'
});Time input formatting with 12/24 hour support.
interface TimeOptions {
time: boolean; // Enable time formatting
timePattern?: string[]; // Time pattern tokens (default: ['h', 'm', 's'])
timeFormat?: '12' | '24'; // Time format (default: '24')
}Usage Examples:
// 24-hour format
const time24 = new Cleave('#time24', {
time: true,
timePattern: ['h', 'm'],
timeFormat: '24'
});
// 12-hour format with seconds
const time12 = new Cleave('#time12', {
time: true,
timePattern: ['h', 'm', 's'],
timeFormat: '12'
});Number formatting with decimal, grouping, and prefix options.
interface NumeralOptions {
numeral: boolean; // Enable numeral formatting
numeralDecimalMark?: string; // Decimal separator (default: '.')
numeralIntegerScale?: number; // Max integer digits (default: 0 = unlimited)
numeralDecimalScale?: number; // Max decimal digits (default: 2)
numeralThousandsGroupStyle?: 'thousand' | 'lakh' | 'wan' | 'none'; // Grouping style
numeralPositiveOnly?: boolean; // Only allow positive numbers (default: false)
stripLeadingZeroes?: boolean; // Remove leading zeros (default: true)
signBeforePrefix?: boolean; // Place sign before prefix (default: false)
tailPrefix?: boolean; // Place prefix at end (default: false)
}Usage Examples:
// Currency formatting
const currency = new Cleave('#currency', {
numeral: true,
numeralDecimalScale: 2,
numeralThousandsGroupStyle: 'thousand',
prefix: '$',
numeralPositiveOnly: true
});
// Indian number system (lakh)
const indianNumber = new Cleave('#indian', {
numeral: true,
numeralThousandsGroupStyle: 'lakh',
numeralDecimalMark: '.',
delimiter: ','
});Block-based formatting for custom patterns.
interface GeneralOptions {
blocks?: number[]; // Length of each formatting block
delimiter?: string; // Single delimiter character
delimiters?: string[]; // Multiple different delimiters
delimiterLazyShow?: boolean; // Show delimiter only when needed
prefix?: string; // Text prefix
noImmediatePrefix?: boolean; // Don't show prefix immediately
rawValueTrimPrefix?: boolean; // Remove prefix from raw value
copyDelimiter?: boolean; // Include delimiters when copying
}Usage Examples:
// License plate format: ABC-1234
const licensePlate = new Cleave('#license', {
blocks: [3, 4],
delimiter: '-',
uppercase: true
});
// Multiple delimiters: 12/34-5678
const multiDelimiter = new Cleave('#multi', {
blocks: [2, 2, 4],
delimiters: ['/', '-']
});
// Prefix example: +1 234-567-8900
const prefixExample = new Cleave('#prefix', {
prefix: '+1 ',
blocks: [3, 3, 4],
delimiter: '-'
});
// Copy delimiter example: Copy includes delimiters
const copyWithDelimiters = new Cleave('#copy', {
blocks: [4, 4, 4, 4],
delimiter: '-',
copyDelimiter: true // When user copies, includes delimiters in clipboard
});Text transformation and filtering options.
interface TextProcessingOptions {
numericOnly?: boolean; // Only allow numeric characters
uppercase?: boolean; // Convert to uppercase
lowercase?: boolean; // Convert to lowercase
}Usage Examples:
// Uppercase alpha-numeric code
const code = new Cleave('#code', {
blocks: [4, 4],
delimiter: '-',
uppercase: true
});
// Numeric only input
const numeric = new Cleave('#numeric', {
numericOnly: true,
blocks: [3, 3, 4]
});Event callback system for responding to input changes.
/**
* Value change callback fired on input changes
* @param event - Change event object
*/
interface CleaveChangeEvent {
target: {
name: string; // Input element name attribute
value: string; // Formatted display value
rawValue: string; // Raw unformatted value
};
}
interface EventOptions {
onValueChanged?: (event: CleaveChangeEvent) => void;
}Usage Examples:
const cleave = new Cleave('#input', {
creditCard: true,
onValueChanged: function (event) {
console.log('Formatted:', event.target.value);
console.log('Raw:', event.target.rawValue);
console.log('Input name:', event.target.name);
// Update other UI elements
document.getElementById('display').textContent = event.target.value;
}
});Advanced configuration options for specialized use cases.
interface AdvancedOptions {
swapHiddenInput?: boolean; // Create hidden input with raw value
initValue?: string; // Initial value to format
document?: Document; // Custom document object (for iframe/worker usage)
}Usage Examples:
// Hidden input pattern - creates hidden field with raw value
const hiddenInputCleave = new Cleave('#visible-input', {
creditCard: true,
swapHiddenInput: true
});
// This creates a hidden input with the raw value alongside the formatted visible input
// Custom document (for iframe usage)
const iframeCleave = new Cleave('#iframe-input', {
creditCard: true,
document: iframe.contentDocument
});
// Initial value formatting
const prefilledCleave = new Cleave('#prefilled', {
creditCard: true,
initValue: '4111111111111111' // Will be formatted on load
});Install with Tessl CLI
npx tessl i tessl/npm-cleave-js