### Install iMask.js Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Install the iMask.js library using npm. This is the first step to begin using the library in your project. ```shell npm install imask ``` -------------------------------- ### Install and Import imaskjs (NPM) Source: https://github.com/unmanner/imaskjs/blob/master/README.md This snippet shows how to install the imaskjs library using npm and import it into your project. It's the standard way to get started if you're using a module bundler. ```bash npm install imask import IMask from 'imask'; ``` -------------------------------- ### Install react-imask Plugin Source: https://github.com/unmanner/imaskjs/blob/master/packages/react-imask/README.md This command installs the react-imask plugin using npm. Ensure you have Node.js and npm installed on your system. ```bash npm install react-imask ``` -------------------------------- ### Install and Import imaskjs (CDN) Source: https://github.com/unmanner/imaskjs/blob/master/README.md This snippet demonstrates how to include imaskjs in your HTML file using a CDN link. This is a convenient option for quick setups or when not using a module bundler. ```html ``` -------------------------------- ### IMaskJS: Basic Pattern Mask Configuration Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates the basic setup for a pattern mask using IMaskJS. It defines a mask string with special characters representing digits, letters, and fixed parts. This is useful for creating complex input formats. ```javascript IMask(element, { mask: '{#}000[aaa]/NIC-`*[**]' // Example pattern string }); // Or without a UI element: IMask.PatternMasked({ mask: '{#}000[aaa]/NIC-`*[**]' }); ``` -------------------------------- ### Range Input Autofixing with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This example showcases the autofix functionality for range inputs in IMaskJS. It allows setting a 'from' and 'to' limit, with options to control autofix behavior (true, false, or 'pad'). Dependencies: IMaskJS library. ```javascript var autofixMask = IMask( document.getElementById('range-autofix-mask'), { mask: IMask.MaskedRange, from: 0, to: 15, autofix: false } ); var selectAutofix = document.getElementById('select-autofix'); selectAutofix.addEventListener('change', function (e) { var val = e.target.value; autofixMask.updateOptions({ autofix: val === 'false' ? false : val === 'true' ? true : 'pad', }); }); ``` -------------------------------- ### Install and Import IMask JavaScript Library Source: https://github.com/unmanner/imaskjs/blob/master/packages/imask/README.md Installation instructions for the imaskjs library using npm package manager or CDN. The npm approach requires importing the IMask module into your project, while the CDN approach adds the library via script tag for direct browser usage. ```javascript npm install imask import IMask from 'imask'; ``` ```html ``` -------------------------------- ### Angular IMask Setup Source: https://github.com/unmanner/imaskjs/blob/master/packages/angular-imask/README.md This code demonstrates how to import and include the IMaskModule in your Angular application's NgModule to enable the IMask directive and pipe. ```javascript import { IMaskModule } from 'angular-imask'; @NgModule({ imports: [ IMaskModule, ... ], ... }) {...} ``` -------------------------------- ### IMaskJS: Skip Invalid Mode Example Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Sets up a 6-digit mask with `skipInvalid` enabled, demonstrating how invalid characters are ignored during input. ```javascript IMask( document.getElementById('skipInvalid-mask'), { mask: '000000', skipInvalid: , } ) ``` -------------------------------- ### Get and Set Mask Values Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates how to retrieve and set the masked and unmasked values of an input mask. This is crucial for interacting with user input. ```javascript mask.value = '+7(999)999-99-99'; console.log(mask.value); // '+7(999)999-99-99' console.log(mask.unmaskedValue); // '79999999999' mask.unmaskedValue = '70000000000'; console.log(mask.value); // '+7(000)000-00-00' console.log(mask.unmaskedValue); // '70000000000' ``` -------------------------------- ### Dispatching Phone Numbers by Country with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This example shows how IMaskJS can dispatch input based on provided patterns and country codes. It allows for different mask formats for various countries like Greece, Russia, and India. Dependencies: IMaskJS library. ```javascript var dispatchMask = IMask( document.getElementById('dispatch-mask'), { mask: [ { mask: '+00 {21} 0 000 0000', startsWith: '30', lazy: false, country: 'Greece' }, { mask: '+0 000 000-00-00', startsWith: '7', lazy: false, country: 'Russia' }, { mask: '+00-0000-000000', startsWith: '91', lazy: false, country: 'India' }, { mask: '0000000000000', startsWith: '', country: 'unknown' } ], dispatch: function (appended, dynamicMasked) { var number = (dynamicMasked.value + appended).replace(/\D/g,''); return dynamicMasked.compiledMasks.find(function (m) { return number.indexOf(m.startsWith) === 0; }) || this.dynamicMasked.compiledMasks[this.dynamicMasked.compiledMasks.length-1]; } } ).on('accept', function() { document.getElementById('dispatch-value').innerHTML = dispatchMask.masked.currentMask.country; }); ``` -------------------------------- ### Format Values with IMaskJS Pipe Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Illustrates using IMask.createPipe and IMask.pipe for formatting and converting values. It supports custom mask options and different data types for input and output. ```javascript const numberPipe = IMask.createPipe({ mask: Number, scale: 2, thousandsSeparator: ' ', normalizeZeros: true, padFractionalZeros: true }); numberPipe('1'); // "1,00" IMask.pipe('1', { mask: Number, scale: 2, thousandsSeparator: ' ', normalizeZeros: true, padFractionalZeros: true }); // "1,00" ``` ```javascript // PIPE_TYPE = {TYPED, MASKED, UNMASKED} IMask.pipe( '1,01', { mask: Number, scale: 2, thousandsSeparator: ' ', normalizeZeros: true, padFractionalZeros: true }, IMask.PIPE_TYPE.MASKED, IMask.PIPE_TYPE.TYPED ); // 1.01 of number type ``` -------------------------------- ### Import iMask.js Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Import the iMask library into your project using either ES modules or CommonJS syntax. This makes the library's functionalities available for use. ```javascript import IMask from 'imask'; ``` -------------------------------- ### IMaskJS: Overwrite Mode Example Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Configures a 6-digit mask in overwrite mode, allowing new characters to replace existing ones instead of inserting. ```javascript IMask( document.getElementById('overwrite-mask'), { mask: '000000', lazy: false, } ) ``` -------------------------------- ### Install vue-imask Package Source: https://github.com/unmanner/imaskjs/blob/master/packages/vue-imask/README.md Install the vue-imask package via npm. For Vue 2, additional composition API dependencies are required. NuxtJS with Vue 2 requires @nuxtjs/composition-api module configuration. ```bash npm i vue-imask ``` ```bash npm i -D @vue/composition-api ``` ```bash npm i -D @nuxtjs/composition-api ``` -------------------------------- ### IMaskJS: Initialize with RegExp Mask Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Initializes IMask with a regular expression to mask input, allowing only digits. ```javascript const digitsMask = IMask(element, { mask: /^\d+$/ }); ``` -------------------------------- ### Date Masking with Lazy Loading and Autofix in IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This example shows a date mask configuration in IMaskJS that supports lazy loading and autofixing. It defines specific blocks for day, month, and year with custom range constraints. Dependencies: IMaskJS library. ```javascript var lazyMask = IMask( document.getElementById('pattern-lazy-mask'), { mask: Date, lazy: false, autofix: true, blocks: { d: { mask: IMask.MaskedRange, placeholderChar: 'd', from: 1, to: 31, maxLength: 2 }, m: { mask: IMask.MaskedRange, placeholderChar: 'm', from: 1, to: 12, maxLength: 2 }, Y: { mask: IMask.MaskedRange, placeholderChar: 'y', from: 1900, to: 2999, maxLength: 4 } } } ); var togglelazy = document.getElementById('toggle-pattern-lazy-mask'); togglelazy.addEventListener('change', function (e) { lazyMask.updateOptions({ lazy: e.target.checked, }); }); ``` -------------------------------- ### IMaskJS: Number Mask Configuration Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Initializes IMask with the Number mask type, configuring options for scale, thousands separator, radix character, padding, normalization, and numerical limits. ```javascript IMask(element, { mask: Number, // enable number mask // other options are optional with defaults below scale: 2, // digits after point, 0 for integers thousandsSeparator: '', // any single char padFractionalZeros: false, // if true, then pads zeros at end to the length of scale normalizeZeros: true, // appends or removes zeros at ends radix: ',', // fractional delimiter mapToRadix: ['.'], // symbols to process as radix // additional number interval options (e.g.) min: -10000, max: 10000, autofix: true, }) ``` -------------------------------- ### Phone Number Mask Initialization and Event Handling (JavaScript) Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This example demonstrates initializing an IMask.js phone number mask on an HTML element. It includes event listeners for 'accept' and 'complete' to update the UI with the unmasked value and indicate completion. The mask format is '+{7}(000)000-00-00'. ```javascript document.addEventListener("DOMContentLoaded", function () { var startPhoneMask = IMask(document.getElementById('start-phone-mask'), { mask: '+{7}(000)000-00-00' }).on('accept', function() { document.getElementById('start-phone-complete').style.display = ''; document.getElementById('start-phone-unmasked').innerHTML = startPhoneMask.unmaskedValue; }).on('complete', function() { document.getElementById('start-phone-complete').style.display = 'inline-block'; }); // ... other masks ``` -------------------------------- ### Basic Input Mask Implementation Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Apply a simple phone number mask to an HTML input element. This involves selecting the element, defining mask options, and creating a mask instance. ```javascript const element = document.getElementById('selector'); const maskOptions = { mask: '+{7}(000)000-00-00' }; const mask = IMask(element, maskOptions); ``` -------------------------------- ### Listen to Mask Events Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Subscribe to mask events like 'accept' and 'complete' to react to changes in the input value. The 'accept' event fires on every change, while 'complete' fires when the mask is fully filled. ```javascript const log = () => console.log(mask.value); // 'accept' event fired on input when mask value has changed mask.on('accept', log); // 'complete' event fired when the value is completely filled // Note: this makes sense only for Pattern-based masks mask.on('complete', () => console.log(mask.value)); ``` -------------------------------- ### Angular IMask Directive Usage Source: https://github.com/unmanner/imaskjs/blob/master/packages/angular-imask/README.md Example of using the imask directive on an input element. It shows how to configure the mask, control unmasking behavior, and handle input events like 'accept' and 'complete'. ```html [unmask]="true" (accept)="onAccept" (complete)="onComplete" [imaskElement]="(elementRef, directiveRef) => maskElement" /> ``` -------------------------------- ### Create Dynamic Mask with Multiple Format Options in IMask.js Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Implements dynamic masking that automatically selects the best-fitting mask from an array of options. Demonstrates color input supporting both RGB (0-255) and HEX (#000000) formats. ```javascript IMask(element, { mask: [ { mask: 'RGB,RGB,RGB', blocks: { RGB: { mask: IMask.MaskedRange, from: 0, to: 255 } } }, { mask: /^#[0-9a-f]{0,6}$/i } ] }) ``` -------------------------------- ### Apply RegExp Mask (Russian Postal Code) with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/index.html Applies a regular expression mask to an input field for Russian postal codes. The mask validates that the input starts with a digit from 1 to 6, followed by 0 to 5 digits. Requires the IMaskJS library. ```javascript IMask( document.getElementById('regexp-mask'), { mask: /^\[1-6\\]\\d{0,5}$/ } ) ``` -------------------------------- ### Implement Dynamic Mask Switching (Phone or Email) with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/index.html Applies a dynamic mask that allows the input to accept either a phone number pattern or an email pattern based on user input. This is achieved by providing an array of masks to the IMask constructor. Requires IMaskJS. ```javascript IMask( document.getElementById('dynamic-mask'), { mask: [ { mask: '+{7}(000)000-00-00' }, { mask: /^\\S*@?\\S*$/ } ] } ) ``` -------------------------------- ### IMaskJS: Prepare Input with Uppercase Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Configures IMask to automatically convert input characters to uppercase using the `prepareChar` option and demonstrates a post-processing hook with `commit`. ```javascript IMask(element, { mask: /^\w+$/, prepareChar: str => str.toUpperCase(), commit: (value, masked) => { // Don't change value manually! All changes should be done in mask! // This example helps to understand what is really changes, only for demo masked._value = value.toLowerCase(); // Don't do it } }) ``` -------------------------------- ### Implement Currency Input with Nested Mask using IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/index.html Creates a currency input mask where the '$' symbol is fixed, and a nested number mask handles the numerical value with thousands separators. This allows for formatted currency input. Requires IMaskJS. ```javascript IMask( document.getElementById('currency-mask'), { mask: '$num', blocks: { num: { mask: Number, thousandsSeparator: ' ' } } } ) ``` -------------------------------- ### Expose Dynamic Mask Value with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates how to expose nested mask values using the 'expose' option within the IMask configuration. This allows access to specific block values for dynamic manipulation. ```javascript IMask(element, { mask: [ { mask: '' }, { mask: 'd %', lazy: false, expose: true, blocks: { d: { mask: Number, expose: true } } } ] }) ``` -------------------------------- ### IMaskJS: Get/Set Value and Unmasked Value Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Shows how to retrieve the current masked value, the unmasked value, and the typed value from an IMask instance. ```javascript masked.value = 'hello world!'; console.log(masked.unmaskedValue); // or typed value if it makes sense console.log(masked.typedValue); ``` -------------------------------- ### IMaskJS: Eager Mode Configuration Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Sets up an input field to use eager mode in IMaskJS. Eager mode processes input immediately as it's typed, unlike lazy mode which waits for interaction. ```javascript IMask(document.getElementById('pattern-eager-mask'), { mask: '00##00##', eager: true // Enable eager mode }) ``` -------------------------------- ### Angular Module Setup for IMaskJS Source: https://context7.com/unmanner/imaskjs/llms.txt Sets up the Angular module to use IMaskJS directives and pipes. This involves importing `IMaskModule` into your application's root or feature module. Requires `angular-imask` package. ```typescript // Module setup import { NgModule } from '@angular/core'; import { IMaskModule } from 'angular-imask'; @NgModule({ imports: [IMaskModule], // ... }) export class AppModule {} ``` -------------------------------- ### Create a Pipe for Unmasked to Masked Value Transformation with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/index.html Creates a pipe function that transforms unmasked input values to their masked representation. This is useful for processing user input before it's displayed or submitted. Requires IMaskJS. ```javascript IMask.createPipe( phoneMask.masked, IMask.PIPE_TYPE.UNMASKED, IMask.PIPE_TYPE.MASKED ) ``` -------------------------------- ### IMaskJS: Update Mask Options Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates how to update IMask options, specifically changing the mask type. Note that changing mask types dynamically is restricted. ```javascript mask.updateOptions({ // while changing mask only same type allowed mask: /^\w+$/, // ok // mask: "0000", // ERROR! changing mask type on existing mask is not allowed! // ... other options }); ``` -------------------------------- ### Importing IMask with Treeshaking for Number Masks (JavaScript) Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This snippet shows how to import only the necessary components from IMask.js for treeshaking, specifically for using the number mask. This reduces the overall bundle size by excluding unused features. It requires the 'imask/holder' and 'imask/masked/number' modules. ```javascript // was before // import IMask from 'imask'; // imports all modules // enable treeshaking import IMask from 'imask/holder'; // imports only factory // add needed features import 'imask/masked/number'; // now factory can work with number masks, but not any other // usage is same in both cases IMask(element, { mask: Number }); ``` -------------------------------- ### IMaskJS: Secure Text Entry with Display Character Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates secure text entry for pattern masks in IMaskJS using the `displayChar` option. This masks the input with a specified character, suitable for password or code inputs. ```javascript IMask(element, { mask: '000000', displayChar: '#', // Masks input with '#' lazy: false, overwrite: 'shift' // Overwrite mode }) ``` -------------------------------- ### Dynamic Color Masking with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This snippet demonstrates how to use IMaskJS to dynamically mask and format color values. It handles both RGB arrays and comma-separated strings, converting them to a standard RGB format. Dependencies: IMaskJS library. ```javascript var dynamicMask = IMask( document.getElementById('color-mask'), { mask: [ { mask: /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ }, { mask: /\d{1,3}\,\d{1,3}\,\d{1,3}/ }, { mask: /\d{1,3}\,\d{1,3}/ }, { mask: /\d{1,3}/ }, { mask: /#00000000/ }, { mask: /#000/ }, { mask: /rgb\(000,000,000\)/ }, { mask: /rgba\(000,000,000,0.00\)/ }, { mask: /#000000/ }, { mask: /000.000.000/ }, { mask: /000,000,000/ } ], repeat: Infinity, greedy: false } ).on('accept', function() { var color = dynamicMask.value; if (!(dynamicMask.masked.currentMask.mask instanceof RegExp)) { color = color.split(','); while (color.length < 3) color.push('0'); color = 'rgb(' + color.join(',') + ')'; } document.getElementById('color-box').style.backgroundColor = color; }); ``` -------------------------------- ### IMaskJS: Custom Validator for Intermediate States Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Illustrates using a RegExp mask to validate intermediate input states, ensuring that partial inputs are also valid according to the pattern. ```javascript const masked = IMask.Masked({ mask: /^123$/ }); ``` -------------------------------- ### IMaskJS: Pattern Mask with Placeholder Configuration Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Illustrates configuring a pattern mask in IMaskJS to use a custom placeholder character and control placeholder visibility. The `lazy` option makes the placeholder always visible. ```javascript IMask(element, { mask: '+{7}(000)000-00-00', lazy: false, // Makes placeholder always visible placeholderChar: '#' // Sets '#' as the placeholder character }) ``` -------------------------------- ### IMaskJS: Range Mask Configuration Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates the use of IMaskJS's Range Mask, which extends the Pattern Mask to restrict input within a specified numerical range. It accepts integer values and can utilize placeholders. ```javascript IMask(element, { mask: IMask.MaskedRange, from: 1, to: 90, maxLength: 3, // Optional: sets the length of the mask autofix: true, // Ensures the value stays within bounds lazy: false // Placeholder is always visible }) ``` -------------------------------- ### Repeating Character Masking with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This snippet demonstrates how to configure a mask to repeat a specific character an infinite number of times using IMaskJS. It allows dynamic updates to the repeat count. Dependencies: IMaskJS library. ```javascript var repeatMask = IMask( document.getElementById('repeat-mask'), { mask: 'r', lazy: false, blocks: { r: { repeat: Infinity, mask: '0', } }, } ); var selectRepeat = document.getElementById('select-repeat'); selectRepeat.addEventListener('change', function (e) { var val = e.target.value; repeatMask.updateOptions({ blocks: { r: { repeat: eval(val), mask: '0', } }, }); }); ``` -------------------------------- ### Eager Input Masking with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This snippet demonstrates the 'eager' option in IMaskJS, which enables immediate masking as the user types. It uses a custom mask pattern '00##00##'. Dependencies: IMaskJS library. ```javascript var eagerMask = IMask( document.getElementById('pattern-eager-mask'), { mask: '00##00##', eager: true, } ); var selectEager = document.getElementById('select-pattern-eager-mask'); selectEager.addEventListener('change', function (e) { var val = e.target.value; eagerMask.updateOptions({ eager: val === 'false' ? false : val === 'true' ? true : val, }); }); ``` -------------------------------- ### Dynamic Mask Definition with IMask.js Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates dynamically changing the mask definition based on input. It supports an array of mask definitions, including a 'RGB,RGB,RGB' format with range blocks and a hex color format ('^#\[0-9a-f\]'). Dependencies: IMask.js. ```javascript var dynamicMask = IMask( document.getElementById('dynamic-mask'), { mask: [ { mask: 'RGB,RGB,RGB', blocks: { RGB: { mask: IMask.MaskedRange, from: 0, to: 255 } } }, { mask: /^#\[0-9a-f\]/ // Incomplete regex in provided snippet } ] }); ``` -------------------------------- ### Apply Number Mask with Range and Thousands Separator using IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/index.html Applies a number mask to an input field, restricting values within a specified range (-10000 to 10000) and formatting numbers with a space as a thousands separator. Requires IMaskJS. ```javascript IMask( document.getElementById('number-mask'), { mask: Number, min: -10000, max: 10000, thousandsSeparator: ' ' } ) ``` -------------------------------- ### Masked TextInput Example in React Native Source: https://github.com/unmanner/imaskjs/blob/master/packages/react-native-imask/README.md Demonstrates how to use the `IMaskTextInput` component for creating masked input fields in React Native. It shows configuration options for masks, unmasking behavior, and event handling, along with basic TextInput styling. ```javascript import {IMaskTextInput} from 'react-native-imask'; console.log(value) // probably should update state } // ...and more mask props in a guide // other TextInput props editable={true} style={{ height: 40, width: '100%', borderColor: 'gray', borderWidth: 1 }} /> ``` -------------------------------- ### IMaskJS: Exposing Block Value in Pattern Mask Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates how to expose the value of a specific block within a pattern mask using the `expose` option in IMaskJS. This is useful when a block's value needs to be directly accessed or used. ```javascript IMask(element, { mask: '$num', lazy: false, blocks: { num: { mask: Number, expose: true // Exposes the value of the 'num' block } } }) ``` -------------------------------- ### Integrate Date Mask with Moment.js in IMask.js Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates date mask integration with Moment.js library for flexible date/time formatting and parsing. Includes custom block definitions for YYYY, MM, DD, HH, mm patterns with range constraints. ```javascript const momentFormat = 'YYYY/MM/DD HH:mm'; IMask(element, { mask: Date, pattern: momentFormat, lazy: false, min: new Date(1970, 0, 1), max: new Date(2030, 0, 1), format: date => moment(date).format(momentFormat), parse: str => moment(str, momentFormat), blocks: { YYYY: { mask: IMask.MaskedRange, from: 1970, to: 2030 }, MM: { mask: IMask.MaskedRange, from: 1, to: 12 }, DD: { mask: IMask.MaskedRange, from: 1, to: 31 }, HH: { mask: IMask.MaskedRange, from: 0, to: 23 }, mm: { mask: IMask.MaskedRange, from: 0, to: 59 } } }); ``` -------------------------------- ### Configure Date Mask with Custom Format and Parse in IMask.js Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Sets up a date mask with custom pattern, format/parse functions, block definitions for day/month/year ranges, and optional min/max date constraints. Validates complete dates after final character insertion. ```javascript IMask(element, { mask: Date, pattern: 'Y-`m-`d', blocks: { d: { mask: IMask.MaskedRange, from: 1, to: 31, maxLength: 2, }, m: { mask: IMask.MaskedRange, from: 1, to: 12, maxLength: 2, }, Y: { mask: IMask.MaskedRange, from: 1900, to: 9999, } }, format: date => { let day = date.getDate(); let month = date.getMonth() + 1; const year = date.getFullYear(); if (day < 10) day = "0" + day; if (month < 10) month = "0" + month; return [year, month, day].join('-'); }, parse: str => { const yearMonthDay = str.split('-'); return new Date(yearMonthDay[0], yearMonthDay[1] - 1, yearMonthDay[2]); }, min: new Date(2000, 0, 1), max: new Date(2020, 0, 1), autofix: true, lazy: false, overwrite: true }) ``` -------------------------------- ### IMaskJS: Pattern Mask with Nested Blocks Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Shows how to create complex nested masks using the `blocks` option in IMaskJS pattern masks. This allows for different mask types within a single input, like ranges or enums. ```javascript IMask(element, { mask: 'Ple\\ase fill ye\\ar 19YY, month MM \\and v\\alue VL', lazy: false, blocks: { YY: { mask: '00' }, MM: { mask: IMask.MaskedRange, from: 1, to: 12 }, VL: { mask: IMask.MaskedEnum, enum: ['TV', 'HD', 'VR'] } } }) ``` -------------------------------- ### Angular IMask Development Build Source: https://github.com/unmanner/imaskjs/blob/master/packages/angular-imask/README.md Commands for building the IMask package and preparing the development environment for the angular-imask package, including running development servers. ```bash npm run make cd packages/angular-imask npm run dev npm run example ``` -------------------------------- ### Initialize Multiple IMaskJS Instances with Event Listeners Source: https://github.com/unmanner/imaskjs/blob/master/docs/index.html This script initializes several IMask instances for different input fields (phone, SSN, regex, number, date, dynamic, currency) and sets up 'accept' event listeners to update corresponding display elements with the unmasked or masked values. It also includes logic for showing completion indicators. Requires IMaskJS. ```javascript document.addEventListener("DOMContentLoaded", function () { var phoneMask = IMask( document.getElementById('phone-mask'), { mask: '+{7}(000)000-00-00' }).on('accept', function() { document.getElementById('phone-complete').style.display = ''; document.getElementById('phone-unmasked').innerHTML = phoneMask.unmaskedValue; }).on('complete', function() { document.getElementById('phone-complete').style.display = 'inline-block'; }); var ssnMask = IMask( document.getElementById('ssn-mask'), { mask: 'XXX-XX-0000', definitions: { X: { mask: '0', displayChar: 'X', placeholderChar: '#', }, }, lazy: false, overwrite: 'shift', }).on('accept', function() { document.getElementById('ssn-complete').style.display = ''; document.getElementById('ssn-value').innerHTML = ssnMask.value; }).on('complete', function() { document.getElementById('ssn-complete').style.display = 'inline-block'; }); var regExpMask = IMask( document.getElementById('regexp-mask'), { mask: /^\[1-6\\]\\d{0,5}$/ }); var numberMask = IMask( document.getElementById('number-mask'), { mask: Number, min: -10000, max: 10000, thousandsSeparator: ' ' }).on('accept', function() { document.getElementById('number-value').innerHTML = numberMask.masked.number; }); var dateMask = IMask( document.getElementById('date-mask'), { mask: Date, min: new Date(1990, 0, 1), max: new Date(2020, 0, 1), lazy: false }).on('accept', function() { document.getElementById('date-value').innerHTML = dateMask.masked.date || '-'; }); var dynamicMask = IMask( document.getElementById('dynamic-mask'), { mask: [ { mask: '+{7}(000)000-00-00' }, { mask: /^\\S*@?\\S*$/ } ] }).on('accept', function() { document.getElementById('dynamic-value').innerHTML = dynamicMask.masked.unmaskedValue || '-'; }); var currencyMask = IMask( document.getElementById('currency-mask'), { mask: '$num', blocks: { num: { mask: Number, thousandsSeparator: ' ' } } }).on('accept', function() { document.getElementById('currency-value').innerHTML = currencyMask.masked.unmaskedValue || '-'; }); var phonePipe = IMask.createPipe(phoneMask.masked, IMask.PIPE_TYPE.UNMASKED, IMask.PIPE_TYPE.MASKED); document.getElementById('pipe-mask').addEventListener('input', function (e) { document.getElementById('pipe-value').innerHTML = phonePipe(e.target.value) || '-'; }); }); ``` -------------------------------- ### Create Repeat Block Pattern Mask in IMask.js Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Shows how to configure repeat block patterns for masked input using the repeat property. Supports infinity, fixed counts, or range arrays [min, max] to repeat mask blocks multiple times. ```javascript IMask( document.getElementById('repeat-mask'), { mask: 'r', lazy: false, blocks: { r: { repeat: , mask: '0', } }, } ) ``` -------------------------------- ### Basic Mask Input Example with IMaskInput Source: https://github.com/unmanner/imaskjs/blob/master/packages/react-imask/README.md Demonstrates how to use the IMaskInput component for creating masked input fields in React. It shows how to configure the mask, handle input values using `onAccept`, and access internal mask properties via refs. Dependencies include React and react-imask. ```javascript import { useRef } from 'react'; import { IMaskInput } from 'react-imask'; // use ref to get access to internal "masked = ref.current.maskRef" const ref = useRef(null); const inputRef = useRef(null); console.log(value) } // ...and more mask props in a guide // input props also available placeholder='Enter number here' /> ``` -------------------------------- ### Skipping Invalid Characters with IMaskJS Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This example shows how to configure IMaskJS to skip invalid characters during input. The 'skipInvalid' option, when enabled, prevents users from entering characters that do not match the mask pattern. Dependencies: IMaskJS library. ```javascript var skipInvalidMask = IMask( document.getElementById('skipInvalid-mask'), { mask: '000000', eager: true, } ); var toggleSkipInvalid = document.getElementById('toggle-skipInvalid-mask'); toggleSkipInvalid.addEventListener('change', function (e) { skipInvalidMask.updateOptions({ skipInvalid: e.target.checked, }); }); ``` -------------------------------- ### Complex Pattern Mask for Multiple Blocks (JavaScript) Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates a complex IMask.js pattern mask designed to accept multiple blocks of information, such as year, month, and value. The mask string includes literal text, placeholders, and escape characters for formatting. This example shows advanced pattern definition. ```javascript var patternGroupsMask = IMask(document.getElementById('pattern-blocks-mask'), { mask: 'Ple\\ase fill ye\\ar 19YY, month MM \\and v\\alue VL' ``` -------------------------------- ### React integration with IMaskJS using IMaskInput component Source: https://context7.com/unmanner/imaskjs/llms.txt Shows how to integrate IMaskJS into React applications using the IMaskInput component. This example demonstrates handling input values, using refs, and implementing onAccept and onComplete callbacks for phone number masking. ```javascript import React, { useState, useRef } from 'react'; import { IMaskInput } from 'react-imask'; // Using IMaskInput component function PhoneInput() { const [value, setValue] = useState(''); const ref = useRef(null); const inputRef = useRef(null); return ( { setValue(value); console.log('Unmasked value:', value); }} onComplete={(value, mask) => { console.log('Input complete:', value); }} placeholder="Enter phone number" /> ); } ``` -------------------------------- ### Vue IMask Directive and Component Setup Source: https://github.com/unmanner/imaskjs/blob/master/packages/vue-imask/example.html Initializes a Vue.js application with the IMask directive and component. It sets up data properties for date and number masks, and configures the composition API hook `useIMask` for a number input. This snippet is essential for setting up the core functionality of the demo. ```javascript var testNumberMask = Number; var testDateMask = { mask: Date }; var app = Vue.createApp({ directives: { imask: VueIMask.IMaskDirective }, components: { 'imask-input': VueIMask.IMaskComponent }, data: () => ({ dateMask: testDateMask, dateValue: '12.12', numberMask: testNumberMask, numberUnmask: 'typed', numberValue: 10, }), setup () { const { el, typed } = VueIMask.useIMask({ mask: Number, scale: 0, }, { defaultTypedValue: 500, onAccept: () => console.log('accept composition value', typed.value), }); return { el }; }, methods: { onAcceptDate: function (e) { console.log('accept date', e.detail.value); this.dateValue = e.detail.value; }, onCompleteDate: function (e) { console.log('complete date!', e.detail.unmaskedValue); }, onFocusNumber: function () { console.log('focus num'); }, onAcceptNumberMasked: function (value, e) { console.log('accept num', value, typeof value); }, onAcceptNumberUnmasked: function (value, e) { console.log('accept num', value, typeof value); }, onCompleteNumber: function (value) { console.log('complete num!', value, typeof value); }, toggleNumberMask: function () { if (app.numberMask) app.numberMask = null; else app.numberMask = testNumberMask; }, toggleDateMask: function () { if (app.dateMask) app.dateMask = null; else app.dateMask = testDateMask; } } }).mount('#app'); ``` -------------------------------- ### Custom Pattern Zip Code Mask with Definitions (JavaScript) Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html This example creates an IMask.js mask for a 5-digit zip code using a custom pattern '#00000'. It defines a custom character '#', mapping it to a regular expression /[1-6]/ to allow digits from 1 to 6 in that position. Event listeners for 'accept' and 'complete' are included. ```javascript var patternZipMask = IMask(document.getElementById('pattern-zip-mask'), { mask: '#00000', definitions: { // : // defaults are '0', 'a', '*' '#': /[1-6]/ } }).on('accept', function() { document.getElementById('pattern-zip-complete').style.display = ''; document.getElementById('pattern-zip-unmasked').innerHTML = patternZipMask.unmaskedValue; }).on('complete', function() { document.getElementById('pattern-zip-complete').style.display = 'inline-block'; }); ``` -------------------------------- ### Build imaskjs (npm) Source: https://github.com/unmanner/imaskjs/blob/master/README.md This command is used to build the imaskjs library, typically when you are contributing to the project or need to generate a custom build. It utilizes npm scripts defined in the project. ```bash npm run make ``` -------------------------------- ### Pattern-Based NIC Mask with Dynamic Updates (JavaScript) Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Demonstrates a complex IMask.js pattern mask for NIC formats, including alphanumeric characters and placeholders. It features lazy input and event handling for displaying unmasked values. Additionally, it includes functionality to dynamically update the mask options (mask, lazy, overwrite, eager, placeholderChar) based on user input and UI elements. ```javascript var customMask = IMask(document.getElementById('pattern-nic-mask'), { mask: '{#}000[aaa]/NIC-`*[**]', lazy: false }); customMask.on('accept', function() { document.getElementById('pattern-nic-complete').style.display = ''; document.getElementById('pattern-nic-unmasked').innerHTML = customMask.unmaskedValue; }).on('complete', function() { document.getElementById('pattern-nic-complete').style.display = 'inline-block'; }); var customEl = document.getElementsByClassName('pattern-nic-form')[0]; customEl.querySelector('[name=apply]').addEventListener('click', function () { var mask = customEl.querySelector('[name=mask]').value; var lazy = customEl.querySelector('[name=ph-show]').checked; var overwrite = customEl.querySelector('[name=overwrite]').checked; var eager = customEl.querySelector('[name=eager]').checked; var placeholderChar = customEl.querySelector('[name=ph-char]').value || '_'; var value = customEl.querySelector('[name=raw]').value; customEl.querySelector('[name=raw]').value = ''; var unmaskedValue = customEl.querySelector('[name=unmasked]').value; customEl.querySelector('[name=unmasked]').value = ''; customMask.updateOptions({ mask: mask, lazy: lazy, overwrite: overwrite, eager: eager, placeholderChar: placeholderChar }); if (value) customMask.value = value; if (unmaskedValue) customMask.unmaskedValue = unmaskedValue; }); ``` -------------------------------- ### Stop Listening to Events Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Unsubscribe from mask events to stop receiving notifications. You can remove specific handlers or all handlers for an event. ```javascript mask.off('accept', log); // omit handler argument to unbind all handlers mask.off('complete'); ``` -------------------------------- ### Destroy Mask Instance Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Clean up and remove the mask from an element. This is important for preventing memory leaks when the mask is no longer needed. ```javascript mask.destroy(); ``` -------------------------------- ### Update Mask Options Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Dynamically update the mask's options after initialization. This allows for changing mask behavior, such as setting numeric ranges. ```javascript mask.updateOptions({ mask: Number, min: 0, max: 100 }); // also updates UI ``` -------------------------------- ### Create Masked Input Component with Solid IMask Source: https://github.com/unmanner/imaskjs/blob/master/packages/solid-imask/README.md Demonstrates how to create a reusable masked input component using `createMaskedInput` from `solid-imask`. This component allows for custom masks, lazy input, and placeholder characters. It also shows how to handle `onAccept` and `onComplete` events. ```javascript import { createMaskedInput } from "solid-imask"; const NumberInput = createMaskedInput({ mask: "+{7}(000)000-00-00", lazy: false, // make placeholder always visible placeholderChar: "#", // defaults to "_" }); const App = () => { return (
{ console.log({ value, unmaskedValue, typedValue }); console.log(maskRef); console.log(e); }} onComplete={() => console.log("complete")} >
); }; ``` -------------------------------- ### Create Mask Without UI Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Instantiate a mask model directly without attaching it to an HTML element. This is useful for processing or validating input programmatically. ```javascript const masked = IMask.createMask({ mask: '+7 (000) 000-00-00', // ...and other options }); masked.resolve('71234567890'); // now you can access masked value console.log(masked.value); // and get unmasked value console.log(masked.unmaskedValue); ``` -------------------------------- ### Access Masked Model Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Retrieve the underlying `Masked` model instance from the mask. This allows for direct manipulation of the masking logic without necessarily updating the UI. ```javascript const masked = mask.masked; masked.reset(); // UI will NOT be updated ``` -------------------------------- ### Initialize IMask with Multiple Document Masks in JavaScript Source: https://github.com/unmanner/imaskjs/blob/master/packages/imask/example.html Sets up IMask with two mask patterns for Brazilian documents (CPF: 000.000.000-00 and CNPJ: 00.000.000/0000-00). Attaches an 'accept' event listener to update DOM elements with masked and unmasked values. The input element references are retrieved from the document and IMask instance properties are logged on value acceptance. ```javascript const opts = { mask: [ { mask: '000.000.000-00' }, { mask: '00.000.000/0000-00' } ] }; const input = document.getElementById('input'); var result = document.getElementById('value'); var unmasked = document.getElementById('unmasked'); var imask = IMask(input, opts).on('accept', () => { console.log('accept', imask.value, imask.unmaskedValue, imask.typedValue); result.innerHTML = imask.value; unmasked.innerHTML = imask.unmaskedValue; }); ``` -------------------------------- ### IMaskJS: Function Mask for Growing Digits Source: https://github.com/unmanner/imaskjs/blob/master/docs/guide.html Implements a custom function mask that accepts a growing sequence of digits from 0 to 9, validating each character and its relation to the previous one. ```javascript IMask(element, { mask: value => /^\d*$/.test(value) && value.split('').every((ch, i) => { const prevCh = value[i-1]; return !prevCh || prevCh < ch; }) }) ```