### Install Cleave.js via npm Source: https://github.com/nosir/cleave.js/blob/master/README.md Installs the Cleave.js library using npm, making it available for use in your project's dependencies. ```bash npm install --save cleave.js ``` -------------------------------- ### TypeScript Integration for Vanilla and React Source: https://context7.com/nosir/cleave.js/llms.txt Provides examples of using Cleave.js with TypeScript, including installation of type definitions and usage with both vanilla JavaScript and React components. It demonstrates type safety for options and event handlers, enhancing code maintainability and reducing errors. Requires installing `@types/cleave.js`. ```typescript // Install types: npm install --save-dev @types/cleave.js import Cleave = require('cleave.js'); // Vanilla JavaScript usage with types const cleave = new Cleave('.credit-card', { creditCard: true, onCreditCardTypeChanged: (type: string) => { console.log('Card type:', type); } }); // React component with TypeScript import Cleave = require('cleave.js/react'); import * as React from 'react'; interface PaymentState { cardNumber: string; cardType: string; } class PaymentForm extends React.Component<{}, PaymentState> { constructor(props: {}) { super(props); this.state = { cardNumber: '', cardType: 'unknown' }; } onCardChange = (event: React.ChangeEvent) => { this.setState({ cardNumber: event.target.value }); } render() { return ( { this.setState({ cardType: type }); } }} onChange={this.onCardChange} /> ); } } ``` -------------------------------- ### Install Babel Presets for Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Installs the necessary Babel presets for ES2015 and React, which are required for Cleave.js to compile ES6 code. This is a prerequisite for using Cleave.js with modern JavaScript development workflows. ```bash npm install --save babel-preset-es2015 babel-preset-react ``` -------------------------------- ### Cleave.js TypeScript Usage Source: https://github.com/nosir/cleave.js/blob/master/README.md Shows how to import and use Cleave.js in a TypeScript project, including the installation of community-contributed type definitions for better type checking and autocompletion. ```typescript import Cleave = require('cleave.js') ``` -------------------------------- ### Install Babel for Webpack Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Installs Babel core and the Webpack loader, enabling Webpack to transpile ES6 code. This is essential for projects using Webpack to bundle their JavaScript, allowing Cleave.js's ES6 features to be processed. ```bash npm install --save babel-core babel-loader ``` -------------------------------- ### Cleave.js Build and Task Commands Source: https://github.com/nosir/cleave.js/blob/master/README.md Provides essential command-line interface (CLI) commands for managing the Cleave.js project. This includes installing dependencies, building project assets, running tests to ensure code quality, linting the codebase for style consistency, and publishing the package after successful builds and tests. ```bash npm install ``` ```bash gulp build ``` ```bash gulp test ``` ```bash gulp eslint ``` ```bash gulp publish ``` -------------------------------- ### React: Initialize and Get Cleave Instance Reference Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Shows how to obtain a reference to the Cleave.js instance in React using the `onInit` callback. This instance can then be used to call public methods exposed by Cleave.js, such as `setRawValue`. ```javascript onCreditCardInit(cleave) { this.setState({creditCardCleave: cleave}); } ``` ```jsx ``` -------------------------------- ### AMD Inclusion of Cleave.js and Phone Addon (JavaScript) Source: https://github.com/nosir/cleave.js/blob/master/doc/phone-lib-addon.md This example demonstrates how to load Cleave.js and a phone addon using the Asynchronous Module Definition (AMD) pattern. This is common in older front-end projects or specific AMD-based module loaders. The callback function receives the Cleave constructor. ```javascript require(['dist/cleave.min', 'dist/addons/cleave-phone.{country}'], function (Cleave) { var cleave = new Cleave (...) }); ``` -------------------------------- ### Legacy React Component with Cleave (ES5) Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Provides an example of using Cleave.js within a React component defined using `React.createClass`, suitable for older React projects. It shows how to handle input changes and log the formatted and raw values. ```javascript var MyComponent = React.createClass({ onCreditCardChange: function (event) { // formatted pretty value console.log(event.target.value); // raw value console.log(event.target.rawValue); }, render: function () { return ( ); } }); ``` -------------------------------- ### Date Formatting with Cleave.js Source: https://context7.com/nosir/cleave.js/llms.txt Formats date inputs with a specified pattern and delimiter. This example uses 'Y-m-d' pattern and a hyphen delimiter. It also supports setting minimum and maximum date constraints for validation. ```javascript var cleaveDate = new Cleave('.date-input', { date: true, datePattern: ['Y', 'm', 'd'], delimiter: '-', dateMin: '2020-01-01', dateMax: '2025-12-31' }); // Input: 20231125 // Output: 2023-11-25 // Get ISO format var isoDate = cleaveDate.getISOFormatDate(); console.log(isoDate); // "2023-11-25" ``` -------------------------------- ### HTML Usage of v-cleave Directive in Vue.js Source: https://github.com/nosir/cleave.js/blob/master/doc/vue.md This snippet displays how to use the custom v-cleave directive in HTML templates within a Vue.js application. It shows examples for credit card numbers, dates, and numerals. Assumes the v-cleave directive has been registered. ```html ``` -------------------------------- ### Global Vue.js Directive for Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/vue.md This code snippet demonstrates how to register Cleave.js as a global directive in a Vue.js application. It handles the initialization and updates of Cleave.js instances on input elements. Dependencies: Vue.js, Cleave.js. ```javascript 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); } }) ``` -------------------------------- ### AngularJS Basic Usage with Cleave.js Directive Source: https://github.com/nosir/cleave.js/blob/master/doc/angularjs-directive-usage.md Demonstrates the basic setup for using the Cleave.js directive in AngularJS. This involves including the necessary script files and configuring the Angular module and controller to apply the directive to an input field for credit card formatting. ```html ``` ```javascript angular.module('app', ['cleave.js']) .controller('AppController', function($scope) { $scope.onCreditCardTypeChanged = function(type) { $scope.model.creditCardType = type; }; $scope.model = { rawValue: '' }; $scope.options = { creditCard: true, onCreditCardTypeChanged: $scope.onCreditCardTypeChanged }; }); ``` ```html
``` -------------------------------- ### Control Prefix Immediacy with noImmediatePrefix in Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Setting `noImmediatePrefix` to true ensures the prefix is only added after the user starts entering values. This is useful for displaying placeholders. It requires the `numeral` option to be true and a prefix to be set. ```javascript new Cleave('.my-input', { numeral: true, prefix: '$', noImmediatePrefix: true }); ``` -------------------------------- ### Cleave.js: Get Raw Value Source: https://context7.com/nosir/cleave.js/llms.txt Illustrates how to retrieve the unformatted, raw value from an input field managed by Cleave.js. This is useful when you need the plain data without any applied formatting, such as for backend processing. ```javascript var cleave = new Cleave('.input', { numeral: true, prefix: '$', delimiter: ',', rawValueTrimPrefix: true }); // User types: $1,234.56 console.log(cleave.getFormattedValue()); // "$1,234.56" console.log(cleave.getRawValue()); // "1234.56" ``` -------------------------------- ### Numeral Formatting with Cleave.js Source: https://context7.com/nosir/cleave.js/llms.txt Formats numerical inputs with options for decimal marks, thousand separators, decimal scale, and integer scale. This example configures thousands grouping, a period decimal mark, and comma delimiter. It also supports prefixes and retrieving the raw numerical value. ```javascript var cleaveNumeral = new Cleave('.numeral-input', { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalMark: '.', delimiter: ',', numeralDecimalScale: 2, numeralIntegerScale: 7, numeralPositiveOnly: false, prefix: '$', signBeforePrefix: true, rawValueTrimPrefix: true }); // Input: -1234567.89 // Output: -$1,234,567.89 var rawValue = cleaveNumeral.getRawValue(); console.log(rawValue); // "1234567.89" ``` -------------------------------- ### Custom Block Pattern Formatting with Cleave.js Source: https://context7.com/nosir/cleave.js/llms.txt Applies custom formatting patterns defined by block lengths and delimiters. This example creates blocks of 4, 3, and 3 digits separated by hyphens, and restricts input to numeric characters only. It also shows how to add a custom prefix. ```javascript var cleaveCustom = new Cleave('.custom-input', { blocks: [4, 3, 3], delimiter: '-', uppercase: true, numericOnly: true }); // Input: 1234567890 // Output: 1234-567-890 // Custom prefix pattern var cleavePrefix = new Cleave('.prefix-input', { prefix: 'PREFIX-', blocks: [7, 4, 4], delimiter: '-', noImmediatePrefix: false }); // Input: 12345678 // Output: PREFIX-1234-5678 ``` -------------------------------- ### Local Vue.js Directive for Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/vue.md This code snippet shows how to define Cleave.js as a local directive within a Vue.js component. This approach is useful for component-specific formatting. Dependencies: Vue.js, Cleave.js. ```javascript import Cleave from 'cleave.js'; export default { ... directives: { 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); } } } ... } ``` -------------------------------- ### Time Formatting with Cleave.js Source: https://context7.com/nosir/cleave.js/llms.txt Formats time inputs with a specified pattern, delimiter, and time format (12 or 24-hour). This example uses 'h:m:s' pattern and a colon delimiter for 24-hour format. It provides a method to retrieve the time in ISO format. ```javascript var cleaveTime = new Cleave('.time-input', { time: true, timePattern: ['h', 'm', 's'], timeFormat: '24', delimiter: ':' }); // Input: 143045 // Output: 14:30:45 var isoTime = cleaveTime.getISOFormatTime(); console.log(isoTime); // "14:30:45" ``` -------------------------------- ### Configure Delimiter Lazy Show in Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md The `delimiterLazyShow` option, when true, delays adding the delimiter until the user starts typing the next group. This option is ignored by 'phone' and 'numeral' shortcut modes. It requires specifying blocks and a delimiter. ```javascript new Cleave('.my-input', { blocks: [3, 3, 3], delimiter: '-', delimiterLazyShow: true }); ``` -------------------------------- ### Phone Number Formatting with Cleave.js Source: https://context7.com/nosir/cleave.js/llms.txt Formats phone numbers using regional codes and custom delimiters. This example uses the 'US' region code and a hyphen delimiter. It also demonstrates dynamically changing the region code to 'GB'. Requires the cleave-phone.us.js addon. ```javascript // Requires: cleave-phone.us.js addon // HTML: var cleavePhone = new Cleave('#phone', { phone: true, phoneRegionCode: 'US', delimiter: '-' }); // Input: 4151234567 // Output: 415-123-4567 // Dynamic region code change cleavePhone.setPhoneRegionCode('GB'); // Input: 2071234567 // Output: 020 7123 4567 ``` -------------------------------- ### Get ISO Format Date from Cleave.js Input Source: https://github.com/nosir/cleave.js/blob/master/doc/public-methods.md Retrieves the date value from a Cleave.js-enhanced input field in ISO format (YYYY-MM-DD). This method is specifically designed for inputs configured for date formatting. ```javascript cleave.getISOFormatDate(); ``` -------------------------------- ### Get Raw Value from Cleave.js Input Source: https://github.com/nosir/cleave.js/blob/master/doc/public-methods.md Retrieves the unformatted, raw value from a Cleave.js-enhanced input field. This is typically used for sending data to a backend or model, bypassing any Cleave.js formatting or delimiters. ```javascript cleave.getRawValue(); ``` -------------------------------- ### Get Formatted Value from Cleave.js Input Source: https://github.com/nosir/cleave.js/blob/master/doc/public-methods.md Retrieves the currently displayed, formatted value from a Cleave.js-enhanced input field. This value includes any patterns, delimiters, or formatting applied by Cleave.js, similar to the input element's `value` property. ```javascript cleave.getFormattedValue(); ``` -------------------------------- ### Configure Time Pattern in JavaScript using Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Set a specific time pattern for input fields using Cleave.js. Accepts an array of 'h', 'm', 's' to define the pattern. Leading zeros are required for hours, minutes, and seconds. Example patterns include ['h', 'm'] for 24-hour format or ['s', 'm', 'h'] for reversed order. ```javascript new Cleave('.my-input', { time: true, timePattern: ['h', 'm'] }); ``` -------------------------------- ### Set Phone Region Code in Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/public-methods.md Sets or changes the country region code for a Cleave.js phone input. This is primarily used when the user switches countries, for example, via a select dropdown, to ensure correct phone number formatting. ```javascript cleave.setPhoneRegionCode('regionCode'); ``` -------------------------------- ### AngularJS Advanced Usage: Getting Formatted Value with Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/angularjs-directive-usage.md Explains how to retrieve the formatted value from an input field managed by Cleave.js within an AngularJS application. It shows how to use the `onValueChanged` callback to capture the formatted input and display both raw and formatted values. ```javascript angular.module('app', ['cleave.js']) .controller('AppController', function($scope) { $scope.onCreditCardTypeChanged = function(type) { $scope.model.creditCardType = type; }; $scope.onValueChanged = function(e) { $scope.model.formattedValue = e.target.value; }; $scope.model = { creditCardType: '', rawValue: '', formattedValue: '' }; $scope.options = { creditCard: true, onCreditCardTypeChanged: $scope.onCreditCardTypeChanged, onValueChanged: $scope.onValueChanged }; }); ``` ```html

raw (ng-model) value: {{model.rawValue}}

formatted value: {{model.formattedValue}}

type: {{model.creditCardType}}

``` -------------------------------- ### Redux Form Field Component with Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md This snippet shows how to create a stateless React component that acts as a wrapper for Cleave.js within a Redux Form setup. It takes field props from Redux Form and passes them to the Cleave component, enabling formatted input like credit card numbers. No external dependencies are required beyond Cleave.js and Redux Form. ```javascript import Cleave from 'cleave.js/react'; const renderCleaveField = field => ( ) ``` -------------------------------- ### React: Update Cleave Raw Value Programmatically Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Illustrates how to programmatically update the raw value of a Cleave input component in React. This involves getting the Cleave instance via `onInit`, storing it, and then calling `setRawValue`. The `onChange` event captures the updated raw and formatted values. ```javascript class MyComponent extends React.Component { constructor(props, context) { super(props, context); this.state = { creditCardCleave: null, creditCardRawValue: '' }; this.onCreditCardChange = this.onCreditCardChange.bind(this); this.onCreditCardInit = this.onCreditCardInit.bind(this); this.reset = this.reset.bind(this); } onCreditCardChange(event) { this.setState({creditCardRawValue: event.target.rawValue}); } onCreditCardInit(cleave) { this.setState({creditCardCleave: cleave}); } reset() { this.state.creditCardCleave.setRawValue(Math.floor(5000 * Math.random())); } render() { return (

credit card: {this.state.creditCardRawValue}

); } } ReactDOM.render(, document.getElementById('content')); ``` -------------------------------- ### React: Access Underlying Input Element Ref with Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Explains how to get a reference to the underlying HTML input element managed by Cleave.js in React using the `htmlRef` prop. This allows direct manipulation of the input element, such as calling `focus()` or `blur()`. Avoid using this ref for value manipulation. ```javascript class MyComponent extends React.Component { constructor(props, context) { super(props, context); this.onBtnClick = this.onBtnClick.bind(this); } onBtnClick() { this.ccInput.focus(); } render() { return (
this.ccInput = ref } options={{creditCard: true}}/>
); } } ReactDOM.render(, document.getElementById('content')); ``` -------------------------------- ### Instantiate Cleave.js with Constructor Source: https://github.com/nosir/cleave.js/blob/master/doc/constructor.md Creates a new Cleave.js instance by targeting an input element using a CSS selector and applying configuration options. ```javascript var cleave = new Cleave('.my-input', { creditCard: true }); ``` -------------------------------- ### Cleave.js Initialization via ES Module (JavaScript) Source: https://github.com/nosir/cleave.js/blob/master/README.md Illustrates initializing Cleave.js using ES Module syntax, suitable for modern JavaScript development with bundlers like Rollup or WebPack, or directly in browsers supporting ES Modules. ```javascript // Rollup, WebPack import Cleave from 'cleave.js'; var cleave = new Cleave(...) // Browser import Cleave from 'node_modules/cleave.js/dist/cleave-esm.min.js'; var cleave = new Cleave(...) ``` -------------------------------- ### Cleave.js Initialization via AMD (JavaScript) Source: https://github.com/nosir/cleave.js/blob/master/README.md Shows how to initialize Cleave.js and its phone number addon using the Asynchronous Module Definition (AMD) pattern, commonly used in older JavaScript projects or specific module loaders. ```javascript require(['cleave.js/dist/cleave.min', 'cleave.js/dist/addons/cleave-phone.{country}'], function (Cleave) { var cleave = new Cleave (...) }); ``` -------------------------------- ### HTML Inclusion of Cleave.js and Phone Addon (HTML) Source: https://github.com/nosir/cleave.js/blob/master/doc/phone-lib-addon.md This shows the basic HTML structure for including Cleave.js and a country-specific phone lib addon. It assumes you have `cleave.min.js` and `cleave-phone.{country}.js` available in your project. After inclusion, a new Cleave instance can be initialized. ```html ``` -------------------------------- ### Cleave.js Initialization via CommonJS (JavaScript) Source: https://github.com/nosir/cleave.js/blob/master/README.md Demonstrates how to require Cleave.js and its phone number addon in a CommonJS environment, typically used with Node.js or module bundlers. ```javascript var Cleave = require('cleave.js'); require('cleave.js/dist/addons/cleave-phone.{country}'); var cleave = new Cleave(...) ``` -------------------------------- ### ES Module Integration with Bundlers and Native Support Source: https://context7.com/nosir/cleave.js/llms.txt Shows how to integrate Cleave.js using modern ES Module syntax, compatible with bundlers like Webpack and Rollup, as well as native browser ES modules. It covers importing the core library and addons, and demonstrates usage with different configurations. The `import` statement is used for module loading. ```javascript // Using bundler (Webpack, Rollup, etc.) import Cleave from 'cleave.js'; import 'cleave.js/dist/addons/cleave-phone.us'; const cleave = new Cleave('.input', { creditCard: true }); // Browser native ES modules import Cleave from './node_modules/cleave.js/dist/cleave-esm.min.js'; const cleave = new Cleave('.input', { numeral: true, numeralDecimalScale: 2 }); ``` -------------------------------- ### Basic Cleave Constructor for Credit Card Formatting Source: https://context7.com/nosir/cleave.js/llms.txt Instantiates a new Cleave instance to format credit card numbers in real-time. It includes a callback for detecting the credit card type upon input. Supports automatic formatting and type detection. ```javascript var cleave = new Cleave('.credit-card-input', { creditCard: true, onCreditCardTypeChanged: function (type) { console.log('Card type detected:', type); // 'visa', 'mastercard', 'amex', etc. } }); // Input: 4111111111111111 // Output: 4111 1111 1111 1111 ``` -------------------------------- ### CommonJS Module Integration for Node.js/Bundlers Source: https://context7.com/nosir/cleave.js/llms.txt Demonstrates how to import and use Cleave.js within Node.js environments or projects that use CommonJS module syntax (e.g., with Webpack or Browserify). It shows importing the core library and optional phone number addons for specific regions. The `require` function is used for importing modules. ```javascript // Import core library var Cleave = require('cleave.js'); // Import phone number addon for specific country require('cleave.js/dist/addons/cleave-phone.us'); require('cleave.js/dist/addons/cleave-phone.gb'); // Use in application var cleave = new Cleave('.phone-input', { phone: true, phoneRegionCode: 'US' }); // For React var CleaveReact = require('cleave.js/react'); ``` -------------------------------- ### Configure Babel .babelrc Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Sets up the Babel configuration file (.babelrc) to use the 'es2015' and 'react' presets. This tells Babel how to transpile the code for compatibility with different environments and browsers. ```json { "presets": ["es2015", "react"] } ``` -------------------------------- ### Shim Cleave.js and Phone Add-on Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Illustrates how to include Cleave.js and its phone add-on using script tags for direct inclusion in HTML. This method exposes `Cleave` as a global variable, useful for projects that don't use module bundlers. ```html ``` -------------------------------- ### Basic Input Formatting with Cleave.js (JavaScript) Source: https://github.com/nosir/cleave.js/blob/master/README.md Initializes Cleave.js to format an input field for phone numbers. Requires the 'cleave.min.js' script and a country-specific phone script addon. It targets a DOM element with the class '.input-phone'. ```javascript var cleave = new Cleave('.input-phone', { phone: true, phoneRegionCode: '{country}', }) ``` -------------------------------- ### ReactJS Component Usage with Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/README.md Demonstrates how to integrate the Cleave.js React component into a JSX structure. It shows importing the component, setting up event handlers for changes and focus, and passing formatting options for credit card numbers. This component acts as a standard input field, accepting HTML attributes and custom options. ```javascript 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 ( ) } } ``` -------------------------------- ### AngularJS Directive Usage with Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/README.md Explains how to use Cleave.js within an AngularJS application by including the cleave-angular directive module. It details setting up the Angular module, defining a controller with scope variables for model and options, and applying the 'cleave' directive to an HTML input element. This allows for formatted input handling in AngularJS views. ```html ``` ```javascript angular .module('app', ['cleave.js']) .controller('AppController', function ($scope) { $scope.onCreditCardTypeChanged = function (type) { $scope.model.creditCardType = type } $scope.model = { rawValue: '', } $scope.options = { creditCard: { creditCard: true, onCreditCardTypeChanged: $scope.onCreditCardTypeChanged, }, } }) ``` ```html
``` -------------------------------- ### Import Cleave.js React Components Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Imports the necessary Cleave.js components for ReactJS applications. This includes the main Cleave component and specific phone number add-ons, demonstrating how to integrate Cleave.js into a React environment. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import Cleave from 'cleave.js/react'; import CleavePhone from 'cleave.js/dist/addons/cleave-phone.{country}'; ``` -------------------------------- ### Legacy Import Cleave.js React Components (ES5) Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Demonstrates how to import Cleave.js React components using CommonJS `require` for projects that do not support ES6 modules. This approach is suitable for older build systems or environments. ```javascript var Cleave = require('cleave.js/dist/cleave-react'); var CleavePhone = require('cleave.js/dist/addons/cleave-phone.{country}'); ``` -------------------------------- ### ReactJS Component Integration with Cleave.js Source: https://context7.com/nosir/cleave.js/llms.txt Integrates Cleave.js as a React component, providing full event handling for formatted input. It requires the 'cleave.js/react' module and supports custom event callbacks like onCardChange and onCardInit. ```javascript import React from 'react'; import Cleave from 'cleave.js/react'; class PaymentForm extends React.Component { constructor(props) { super(props); this.state = { cardNumber: '', cardType: 'unknown' }; this.onCardChange = this.onCardChange.bind(this); this.onCardInit = this.onCardInit.bind(this); } onCardChange(event) { // Formatted value this.setState({ cardNumber: event.target.value }); // Raw value (without formatting) console.log('Raw value:', event.target.rawValue); } onCardInit(owner) { // Access cleave instance methods console.log('Cleave initialized:', owner); } render() { return (
{ this.setState({ cardType: type }); } }} onChange={this.onCardChange} onInit={this.onCardInit} value={this.state.cardNumber} />

Card Type: {this.state.cardType}

); } } export default PaymentForm; ``` -------------------------------- ### CommonJS Inclusion of Cleave.js and Phone Addon (JavaScript) Source: https://github.com/nosir/cleave.js/blob/master/doc/phone-lib-addon.md This snippet illustrates how to include Cleave.js and a country-specific phone addon using CommonJS module system, typically in a Node.js environment or a project using a module bundler. It requires both the main Cleave library and the addon module. ```javascript var Cleave = require('cleave.js'); require('cleave.js/dist/addons/cleave-phone.{country}'); var cleave = new Cleave(...) ``` -------------------------------- ### AngularJS Directive for Cleave.js Source: https://context7.com/nosir/cleave.js/llms.txt Demonstrates how to integrate Cleave.js into an AngularJS 1.x application using a custom directive. It requires the 'cleave.js' AngularJS module and allows configuration of various formatting options, including credit card, phone, and date. ```javascript // Module setup angular .module('app', ['cleave.js']) .controller('FormController', function($scope) { $scope.model = { rawValue: '' }; $scope.onCreditCardTypeChanged = function(type) { $scope.model.creditCardType = type; }; $scope.options = { creditCard: { creditCard: true, onCreditCardTypeChanged: $scope.onCreditCardTypeChanged }, phone: { phone: true, phoneRegionCode: 'US' }, date: { date: true, datePattern: ['m', 'd', 'Y'] } }; }); ``` ```html

Card Type: {{model.creditCardType}}

``` -------------------------------- ### Cleave.js React Component TypeScript Usage Source: https://github.com/nosir/cleave.js/blob/master/README.md Demonstrates how to import and use the Cleave.js React component types in a TypeScript project, facilitating its integration within React applications with type safety. ```typescript import Cleave = require('cleave.js/react') ``` -------------------------------- ### Browserify Babelify Transform Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Configures Browserify to use the 'babelify' transform with 'es2015' and 'react' presets. This allows Browserify to transpile ES6 code, making Cleave.js compatible with projects using Browserify. ```javascript browserify(...).transform('babelify', {presets: ['es2015', 'react']})... ``` -------------------------------- ### Cleave.js: Destroy Instance Source: https://context7.com/nosir/cleave.js/llms.txt Provides instructions on how to properly clean up and remove event listeners associated with a Cleave.js instance using the destroy method. This is crucial for preventing memory leaks, especially in single-page applications or when components are unmounted. ```javascript var cleave = new Cleave('.input', { creditCard: true }); // Later, when component unmounts or is no longer needed cleave.destroy(); // For React class Example extends React.Component { componentWillUnmount() { if (this.cleave) { this.cleave.destroy(); } } } ``` -------------------------------- ### Date Formatting with Min/Max Boundaries Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Enables Cleave.js date formatting with minimum and maximum date boundaries. Dates must adhere to the ISO 8601 format (YYYY-MM-DD) or a custom pattern if specified. ```javascript new Cleave('.my-input', { date: true, dateMin: '2000-01-01', dateMax: '2099-12-31', datePattern: ['d', 'm', 'Y'] }); ``` ```javascript new Cleave('.my-input', { date: true, dateMin: '18-01', dateMax: '28-12', datePattern: ['m', 'y'] }); ``` -------------------------------- ### Cleave.js: Credit Card Type Detection Source: https://context7.com/nosir/cleave.js/llms.txt Demonstrates Cleave.js's ability to automatically detect credit card types based on input and trigger callbacks with the detected type. It also shows how to use the onValueChanged callback to access both formatted and raw input values. ```javascript var cleave = new Cleave('.cc-input', { creditCard: true, creditCardStrictMode: true, onCreditCardTypeChanged: function(type) { // Update UI based on card type var cardIcon = document.querySelector('.card-icon'); cardIcon.className = 'card-icon ' + type; // Type can be: 'amex', 'visa', 'mastercard', 'discover', // 'diners', 'jcb', 'dankort', 'instapayment', 'uatp', // 'maestro', 'mir', 'unionPay', or 'unknown' }, onValueChanged: function(e) { console.log('Value:', e.target.value); console.log('Raw:', e.target.rawValue); } }); // Input: 4111... // Callback triggered with type: 'visa' // Format applied: 4111 1111 1111 1111 // Input: 3782... // Callback triggered with type: 'amex' // Format applied: 3782 822463 10005 (amex uses 4-6-5 pattern) ``` -------------------------------- ### Include Custom AsYouTypeFormatter with Cleave.js (JavaScript) Source: https://github.com/nosir/cleave.js/blob/master/doc/phone-lib-addon.md This snippet demonstrates how to integrate a custom AsYouTypeFormatter from google-libphonenumber with Cleave.js. It's useful when you need to manage dependencies and reduce bundle size by bringing your own formatter instance. ```javascript const AsYouTypeFormatter = require('google-libphonenumber').AsYouTypeFormatter; window.Cleave = window.Cleave || {}; window.Cleave.AsYouTypeFormatter = AsYouTypeFormatter; ``` -------------------------------- ### Set Raw Value and Apply Formatting in Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/public-methods.md Sets the raw value of a Cleave.js-initialized input field and automatically applies the configured formatting. This method is useful for pre-populating fields or updating them with new data that needs to be formatted. ```javascript cleave.setRawValue('5555444433332222'); ``` -------------------------------- ### Cleave.js: Set Raw Value Programmatically Source: https://context7.com/nosir/cleave.js/llms.txt Shows how to set the value of a Cleave.js instance programmatically using setRawValue. This method accepts the unformatted value and applies the configured Cleave.js formatting. It is also demonstrated within a React component context. ```javascript var cleave = new Cleave('.input', { creditCard: true }); // Set value programmatically cleave.setRawValue('4111111111111111'); console.log(cleave.getFormattedValue()); // "4111 1111 1111 1111" // For React component class Example extends React.Component { componentDidMount() { this.cleaveRef.setRawValue('4111111111111111'); } render() { return ( this.cleaveRef = ref} options={{ creditCard: true }} /> ); } } ``` -------------------------------- ### Define Input Blocks for Formatting in JavaScript using Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Format input values by defining groups using the 'blocks' option in Cleave.js. This inserts delimiters between specified block sizes. This option is ignored for shortcut modes like creditCard, phone, date, and numeral. ```javascript new Cleave('.my-input', { blocks: [2, 5, 5] }); ``` -------------------------------- ### Enable Numeral Input Formatting in JavaScript using Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Activate numeral input formatting for fields using Cleave.js by setting the 'numeral' option to true. This enables shortcut mode for numerical inputs, allowing for various customization options. ```javascript new Cleave('.my-input', { numeral: true }); ``` -------------------------------- ### Webpack Babel Loader Configuration Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Configures Webpack to use the Babel loader for transpiling JavaScript files. This ensures that ES6 code, including Cleave.js, is correctly processed before being bundled. ```javascript loaders: [ { test: ..., exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] ``` -------------------------------- ### React: Set Default Value for Cleave Input Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Demonstrates how to provide an initial default value to a Cleave input component in React. The `value` prop is used for this purpose during the initial render. The `options` prop configures Cleave.js for credit card formatting. ```jsx ``` -------------------------------- ### Control Sign Position for Numerals in JavaScript using Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Determine if the sign of a numeral should appear before or after the prefix using Cleave.js. Set 'signBeforePrefix' to true to place the sign before the prefix (e.g., '-$1234.56'). The default is false. ```javascript new Cleave('.my-input', { numeral: true, prefix: '$', signBeforePrefix: true }); ``` -------------------------------- ### React Component with Cleave Inputs Source: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md Defines a React component that utilizes Cleave.js for formatted input fields, including credit card, phone number, and custom numeric inputs. It demonstrates state management for raw input values and event handling for changes. ```javascript class MyComponent extends React.Component { constructor(props, context) { super(props, context); this.state = { creditCardRawValue: '', phoneRawValue: '', customRawValue: '' }; this.onCreditCardChange = this.onCreditCardChange.bind(this); this.onCreditCardFocus = this.onCreditCardFocus.bind(this); this.onPhoneChange = this.onPhoneChange.bind(this); this.onCustomChange = this.onCustomChange.bind(this); } onCreditCardChange(event) { this.setState({creditCardRawValue: event.target.rawValue}); } onCreditCardFocus(event) { // update some state } onPhoneChange(event) { this.setState({phoneRawValue: event.target.rawValue}); } onCustomChange(event) { this.setState({customRawValue: event.target.rawValue}); } render() { return (

credit card: {this.state.creditCardRawValue}

phone: {this.state.phoneRawValue}

custom: {this.state.customRawValue}

); } } ReactDOM.render(, document.getElementById('content')); ``` -------------------------------- ### Swap Hidden Input for Raw Value Storage Source: https://context7.com/nosir/cleave.js/llms.txt This feature creates a hidden input field to store the raw, unformatted value of an input field, while the visible input displays the formatted value. This is useful for form submissions where the raw data is required. It depends on the Cleave.js library being initialized with the `swapHiddenInput: true` option. ```javascript // HTML: var cleave = new Cleave('.display-input', { creditCard: true, swapHiddenInput: true }); // Result: DOM structure becomes: // (shows formatted value) // (contains raw value) // When form is submitted, the hidden field sends the raw value ``` -------------------------------- ### AngularJS: Calling Cleave.js Public Methods via on-init Callback Source: https://github.com/nosir/cleave.js/blob/master/doc/angularjs-directive-usage.md Details how to access and invoke public methods of a Cleave.js instance within an AngularJS application. This is achieved by utilizing the `on-init` callback provided by the Cleave.js directive, which passes the cleave instance as an argument. ```javascript $scope.onInit = function(cleave) { $scope.model.cleave = cleave; }; // Example usage within the controller, assuming $scope.model.cleave is set // $scope.model.cleave.getISOFormatDate(); ``` -------------------------------- ### Trim Prefix in Raw Value with rawValueTrimPrefix in Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md The `rawValueTrimPrefix` option, when true, trims the prefix when calling `getRawValue()` or accessing `rawValue` in frameworks. This is useful for obtaining the clean numeric value. It requires the `numeral` option to be true and a prefix to be set. ```javascript new Cleave('.my-input', { numeral: true, prefix: '$', rawValueTrimPrefix: true }); ``` -------------------------------- ### Enable Time Formatting Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Enables Cleave.js to format input fields as time values. This option triggers the time shortcut mode for input. ```javascript new Cleave('.my-input', { time: true }); ``` -------------------------------- ### Position Prefix After Numeral in JavaScript using Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Configure the prefix to appear after the numeral value in input fields using Cleave.js. Set 'tailPrefix' to true to achieve this (e.g., '1234.56€'). The default behavior is to place the prefix before the numeral. ```javascript new Cleave('.my-input', { numeral: true, prefix: '€', tailPrefix: true }); ``` -------------------------------- ### Enable Date Formatting with Custom Pattern Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Enables Cleave.js to format input fields as dates, allowing for a custom date pattern to be specified. The pattern uses 'Y' for year, 'm' for month, and 'd' for day. ```javascript new Cleave('.my-input', { date: true, datePattern: ['Y', 'm', 'd'] }); ``` -------------------------------- ### onValueChanged Callback for Input Changes Source: https://context7.com/nosir/cleave.js/llms.txt This functionality allows developers to execute custom JavaScript code whenever the input value changes. The callback function receives an event object containing details about the input, including its name, formatted value, and raw value. It can be used for real-time updates, validation, or triggering other UI interactions. Depends on the `onValueChanged` option being set. ```javascript var cleave = new Cleave('.tracked-input', { numeral: true, onValueChanged: function(e) { console.log('Name:', e.target.name); console.log('Formatted:', e.target.value); console.log('Raw:', e.target.rawValue); // Update other UI elements document.querySelector('.preview').textContent = e.target.value; // Validate if (parseFloat(e.target.rawValue) > 1000) { document.querySelector('.warning').style.display = 'block'; } } }); ``` -------------------------------- ### Set Prefix in Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md The `prefix` option allows you to prepend a string to the input field's value. This prefix cannot be removed or changed by the user. It requires specifying blocks. ```javascript new Cleave('.my-input', { blocks: [6, 3, 3], prefix: '253874' }); ``` -------------------------------- ### Define Multiple Delimiters for Input Formatting in JavaScript using Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Use multiple delimiters for input formatting in Cleave.js by providing an array to the 'delimiters' option. This overrides the single 'delimiter' option. This feature is ignored for shortcut modes. ```javascript new Cleave('.my-input', { blocks: [3, 3, 3, 2], delimiters: ['.', '.', '-'] }); ``` -------------------------------- ### Enable Credit Card Formatting in Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Enables Cleave.js to format input fields as credit card numbers. It dynamically detects the credit card type based on the card's Issuer Identification Number (IIN). ```javascript new Cleave('.my-input', { creditCard: true }); ``` -------------------------------- ### Enable Strict Mode for Credit Card Formatting Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Enables strict mode for credit card formatting in Cleave.js, which supports extended use of 19-digit Primary Account Numbers (PANs) for compatible credit cards. ```javascript new Cleave('.my-input', { creditCard: true, creditCardStrictMode: true }); ``` -------------------------------- ### Set Thousands Grouping Style in JavaScript using Cleave.js Source: https://github.com/nosir/cleave.js/blob/master/doc/options.md Customize the thousands separator grouping style for numeral inputs with Cleave.js. Options include 'thousand' (e.g., 1,234,567.89), 'lakh' (Indian style, e.g., 12,34,567.89), 'wan' (Chinese style, e.g., 123,4567.89), and 'none' (no grouping). ```javascript new Cleave('.my-input', { numeral: true, numeralThousandsGroupStyle: 'wan' }); ```