### Install Maskito Core and React
Source: https://maskito.dev/frameworks/react
Installs the core Maskito library and the React integration package using npm.
```bash
npm install @maskito/{core,react}
```
--------------------------------
### Install Maskito for Vue
Source: https://maskito.dev/frameworks/vue
Installs the core Maskito library and the Vue integration package using npm.
```bash
npm install @maskito/{core,vue}
```
--------------------------------
### Install @maskito/kit
Source: https://maskito.dev/getting-started/maskito-libraries
Installs the optional @maskito/kit package, which provides ready-to-use, configurable masks for various input types. It's framework-agnostic.
```bash
npm install @maskito/kit
```
--------------------------------
### Install @maskito/core
Source: https://maskito.dev/getting-started/maskito-libraries
Installs the core Maskito package, which is framework-agnostic and zero-dependency. It's essential for other Maskito packages and can be used in vanilla JavaScript projects.
```bash
npm install @maskito/core
```
--------------------------------
### Install @maskito/react
Source: https://maskito.dev/getting-started/maskito-libraries
Installs the React-specific Maskito library, providing a hook for using Maskito within React applications.
```bash
npm install @maskito/react
```
--------------------------------
### Install @maskito/vue
Source: https://maskito.dev/getting-started/maskito-libraries
Installs the Vue-specific Maskito library, allowing Maskito to be used as a directive in Vue applications.
```bash
npm install @maskito/vue
```
--------------------------------
### Install Maskito Angular Package
Source: https://maskito.dev/frameworks/angular/Setup
Installs the core Maskito library and the Angular-specific module using npm. This is the first step to enable input masking in your Angular application.
```bash
npm install @maskito/{core,angular}
```
--------------------------------
### Install @maskito/angular
Source: https://maskito.dev/getting-started/maskito-libraries
Installs the Angular-specific Maskito library, enabling the use of Maskito as a directive within Angular applications.
```bash
npm install @maskito/angular
```
--------------------------------
### React Hook Form Integration Example
Source: https://maskito.dev/frameworks/react
Provides an example of integrating Maskito with the popular 'react-hook-form' library, demonstrating how to manage masked input values within form state.
```jsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { useMaskito } from '@maskito/react';
function ReactHookFormMaskedInput() {
const { register, handleSubmit } = useForm();
const inputRef = useMaskito({
mask: /\d/,
});
const onSubmit = (data) => console.log(data);
return (
);
}
```
--------------------------------
### Install @maskito/phone
Source: https://maskito.dev/getting-started/maskito-libraries
Installs the optional @maskito/phone package for international phone number masking. It relies on the libphonenumber-js library.
```bash
npm install @maskito/phone
```
--------------------------------
### Example Preprocessor: Standardize Decimal Separator
Source: https://maskito.dev/core-concepts/processors
An example of a Maskito preprocessor that replaces all periods with commas in both the element's value and the input data, ensuring a consistent decimal separator.
```javascript
const numberInput = new Maskito(element, {
mask: /^\d+(,\d*)?$/, // digits and comma (as decimal separator)
preprocessors: [
({elementState, data}, actionType) => {
const {value, selection} = elementState;
return {
elementState: {
selection,
value: value.replace('.', ','),
},
data: data.replace('.', ','),
};
},
],
});
```
--------------------------------
### React Integration
Source: https://maskito.dev/kit/time
Provides an example of integrating Maskito time masking into a React application using the `useMaskito` hook. This hook simplifies the process of applying masks to input elements in React.
```javascript
import * as React from 'react';
import {useMaskito} from '@maskito/react';
import options from './mask';
export default function App(
const maskedInputRef = useMaskito({options});
return ;
}
```
--------------------------------
### Vanilla JavaScript Lazy Metadata Loading
Source: https://maskito.dev/addons/phone
Shows how to implement lazy metadata loading for phone number masking using vanilla JavaScript. This example initializes Maskito with dynamically imported phone metadata, providing a flexible way to manage dependencies.
```javascript
import {Maskito, MASKITO_DEFAULT_OPTIONS} from '@maskito/core';
import {maskitoPhoneOptionsGenerator} from '@maskito/phone';
const element = document.querySelector('input,textarea');
let maskedInput;
(async function initMask(
const maskitoOptions = maskitoPhoneOptionsGenerator({
countryIsoCode: 'RU',
metadata: await import('libphonenumber-js/min/metadata').then((m) => m.default),
});
maskedInput = new Maskito(element, maskitoOptions);
})();
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Number Mask Generation and Usage
Source: https://maskito.dev/kit/number
Demonstrates how to generate number input masks using `maskitoNumberOptionsGenerator` and how to parse and stringify numbers with custom parameters. Includes examples for basic configuration, parsing, and stringifying.
```typescript
import {
MaskitoNumberParams,
maskitoParseNumber,
maskitoStringifyNumber,
maskitoNumberOptionsGenerator,
} from '@maskito/kit';
const params: MaskitoNumberParams = {
decimalSeparator: ',', // default is '.'
};
maskitoNumberOptionsGenerator(params); // MaskitoOptions
maskitoParseNumber('10 000,42', params); // 10000.42
maskitoStringifyNumber(10000.42, params); // '10 000,42'
```
--------------------------------
### Maskito Integration with Vue
Source: https://maskito.dev/kit/number
Demonstrates integrating Maskito into a Vue.js application using the `v-maskito` directive. The example shows how to register the directive and pass the mask options to the input element.
```javascript
import {createApp} from 'vue';
import {maskito} from '@maskito/vue';
import options from './mask';
const app = createApp({
template: '',
directives: {maskito},
data: () => ({ options }),
});
```
--------------------------------
### Maskito Postprocessor Example
Source: https://maskito.dev/core-concepts/processors
Demonstrates a Maskito postprocessor that prevents repeated leading zeros in a numeric input. It accepts the current element state and the initial state, processes the value to remove extra leading zeros, and returns the updated value and selection range.
```typescript
import {Maskito} from '@maskito/core';
const numberInput = new Maskito(element, {
mask: /^\d+(,\d*)?$/, // Example mask for numbers with optional decimal part
postprocessors: [
({value, selection}, initialElementState) => {
const [from, to] = selection;
// Remove repeated leading zeros, but keep a single zero if the value starts with it
const noRepeatedLeadingZeroesValue = value.replace(/^0+/, '0');
const removedCharacters = value.length - noRepeatedLeadingZeroesValue.length;
return {
value: noRepeatedLeadingZeroesValue, // User types "000000" => 0|
// Adjust selection range based on removed characters
selection: [Math.max(from - removedCharacters, 0), Math.max(to - removedCharacters, 0)],
};
},
],
});
```
--------------------------------
### Programmatic Value Setting Template
Source: https://maskito.dev/frameworks/angular
The HTML template for the programmatic value setting example, featuring an input with `formControl` and `maskito` directives, and a button to trigger the value update.
```HTML
```
--------------------------------
### Vue Integration
Source: https://maskito.dev/kit/time
Shows how to apply Maskito time masking in a Vue.js application using the `v-maskito` directive. This example demonstrates registering the directive and passing the mask options to the input element.
```javascript
import {createApp} from 'vue';
import {maskito} from '@maskito/vue';
import options from './mask';
const app = createApp({
template: '',
directives: {maskito},
data: () => ({ options }),
});
```
--------------------------------
### Angular Value Formatting with MaskitoPipe
Source: https://maskito.dev/frameworks/angular
Illustrates how to format a numerical value in an Angular template using the MaskitoPipe. This example formats a balance with a specific number of decimal places using a pre-configured options object generated by maskitoNumberOptionsGenerator.
```typescript
import {ChangeDetectionStrategy, Component} from '@angular/core';
import {MaskitoPipe} from '@maskito/angular';
import {maskitoNumberOptionsGenerator} from '@maskito/kit';
@Component({
standalone: true,
selector: 'pipe-doc-example-4',
imports: [MaskitoPipe],
templateUrl: './template.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PipeDocExample4 {
protected value = 12345.67;
protected readonly options = maskitoNumberOptionsGenerator({
maximumFractionDigits: 2,
});
}
```
```html
Balance: ${{ value | maskito: options }}
```
--------------------------------
### Applying Initial Calibration Plugin
Source: https://maskito.dev/core-concepts/plugins/Built-in_core_plugins
This JavaScript snippet shows how to instantiate Maskito with the `maskitoInitialCalibrationPlugin` and how the plugin corrects an invalid initial value. It also includes the `destroy` method for cleanup.
```javascript
import {Maskito} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input')!;
element.value = '12345'; // patch with invalid initial value
// enable mask
const maskedInput = new Maskito(element, maskitoOptions);
console.info(element.value); // 123
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Initialize Maskito Instance
Source: https://maskito.dev/core-concepts/overview
Demonstrates how to create a new Maskito instance, passing the HTML input element and configuration options. The options include defining the mask, preprocessors, postprocessors, plugins, and overwrite mode. The `destroy` method is shown for cleanup.
```typescript
import {Maskito, maskitoInitialCalibrationPlugin} from '@maskito/core';
const element = document.getElementById('my-input'); // Assume element is an HTMLInputElement
if (element) {
const maskedInput = new Maskito(element, {
mask: /^\d+$/,
preprocessors: [preprocessor1, preprocessor2], // Assume preprocessor1 and preprocessor2 are defined
postprocessors: [
({value, selection}) => {
// Custom postprocessing logic
return { value, selection };
},
],
plugins: [myCustomPlugin, maskitoInitialCalibrationPlugin()], // Assume myCustomPlugin is defined
overwriteMode: 'shift',
});
// Call it when the element is destroyed
// maskedInput.destroy();
}
```
--------------------------------
### DateTime Kit API Documentation
Source: https://maskito.dev/kit/date-time/API
Detailed API documentation for the Maskito DateTime Kit, outlining all available configuration options, their types, default values, and descriptions.
```apidoc
DateTime Kit Configuration:
- dateMode: Date format mode. Type: MaskitoDateMode. Default: 'dd/mm/yyyy'.
- timeMode: Time format mode. Type: MaskitoTimeMode. Default: 'HH:MM'.
- dateSeparator: Separator between date parts. Type: string. Default: '.'.
- dateTimeSeparator: Separator between date and time. Type: string. Default: ', '.
- timeStep: Value for incrementing/decrementing time segments with arrow keys. Type: number. Default: 0 (disabled).
- min: Earliest allowed date. Type: Date. Default: '0001-01-01T00:00:00'.
- max: Latest allowed date. Type: Date. Default: '9999-12-31T23:59:59'.
```
--------------------------------
### Initializing Maskito with Custom Options
Source: https://maskito.dev/kit/time
Demonstrates the core JavaScript usage of Maskito by initializing it on an input element with provided options. It also shows how to destroy the Maskito instance when the element is no longer needed, preventing memory leaks.
```javascript
import { Maskito, MaskitoOptions } from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Vanilla JavaScript Maskito Integration
Source: https://maskito.dev/kit/time
Demonstrates how to initialize Maskito with a given configuration on an HTML input or textarea element using vanilla JavaScript. It also shows how to destroy the Maskito instance when it's no longer needed.
```javascript
import {Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Vanilla JavaScript Integration
Source: https://maskito.dev/kit/time
Demonstrates how to initialize Maskito with the time stepping configuration on an input element using vanilla JavaScript. Includes instructions for destroying the Maskito instance when the element is removed from the DOM.
```javascript
import {Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Maskito Date Kit API Documentation
Source: https://maskito.dev/kit/date/API
API reference for the Maskito Date Kit, detailing configuration options for date formatting and validation.
```apidoc
MaskitoDateMode:
'dd/mm/yyyy': Date format mode for day/month/year.
MaskitoDateOptions:
mode: Date format mode.
Type: MaskitoDateMode
Default: 'dd/mm/yyyy'
separator: Symbol for separating date segments.
Type: string
Default: '.'
min: Earliest allowed date.
Type: Date
Default: new Date('0001-01-01')
max: Latest allowed date.
Type: Date
Default: new Date('9999-12-31')
```
--------------------------------
### Maskito Core Initialization
Source: https://maskito.dev/kit/number
Demonstrates how to initialize Maskito with custom options on a native HTML input or textarea element using the core Maskito API. Includes instructions for cleanup.
```javascript
import {Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Nested Input Template
Source: https://maskito.dev/frameworks/angular
The HTML template for the nested input example, showing a `tui-input` component with Maskito applied and bound to a variable.
```HTML
Name on the card
```
--------------------------------
### Custom Separator for Date and Time
Source: https://maskito.dev/kit/date-time
Customize the separator between the date and time parts of the input using the `dateTimeSeparator` parameter. For example, use a semicolon or a space.
```javascript
import { maskitoDateTimeOptionsGenerator } from '@maskito/kit';
const customSeparatorMask = maskitoDateTimeOptionsGenerator({
dateTimeSeparator: ';',
});
```
--------------------------------
### Basic Maskito Initialization and Destruction
Source: https://maskito.dev/addons/phone
Shows the fundamental steps to initialize Maskito on an input element and how to properly destroy the Maskito instance when it's no longer needed, typically when the element is removed from the DOM.
```javascript
import { Maskito, MaskitoOptions } from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Initialize Maskito with Options
Source: https://maskito.dev/kit/time
Demonstrates how to initialize Maskito on an HTML input or textarea element using provided Maskito options. Includes a method to destroy the Maskito instance when the element is removed from the DOM.
```javascript
import {Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
// maskedInput.destroy();
```
--------------------------------
### Conditional Nested Input with Maskito
Source: https://maskito.dev/frameworks/angular
An example showing a conditional `tui-input` where Maskito is applied. The input's visibility and Maskito's application are controlled by a checkbox.
```HTML
Name on the card
```
--------------------------------
### Initialize Maskito in Vanilla JavaScript
Source: https://maskito.dev/kit/number
Demonstrates how to initialize Maskito on an input or textarea element using vanilla JavaScript. It imports the Maskito core library and the previously defined mask options, then creates a new Maskito instance.
```javascript
import { Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Initialize Maskito Phone Input (Vanilla JS)
Source: https://maskito.dev/addons/phone
Demonstrates how to initialize Maskito for a phone input using vanilla JavaScript. It involves creating a `Maskito` instance with the generated options and provides a method to destroy the instance when the element is detached.
```javascript
import {Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Project Dependencies
Source: https://maskito.dev/stackblitz
Lists the project's dependencies, including core Maskito libraries and the libphonenumber-js library for potential phone number formatting.
```json
{
"dependencies": {
"@maskito/core": "3.10.3",
"@maskito/kit": "3.10.3",
"@maskito/phone": "3.10.3",
"libphonenumber-js": "1.12.10"
}
}
```
--------------------------------
### Angular Non-Strict Phone Input Example
Source: https://maskito.dev/addons/phone
An Angular component demonstrating a non-strict phone number input using Maskito. It integrates with Taiga UI components and uses the `maskitoPhoneOptionsGenerator` to configure the mask.
```typescript
import {ChangeDetectionStrategy, Component, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {MaskitoDirective} from '@maskito/angular';
import {maskitoGetCountryFromNumber} from '@maskito/phone';
import {TuiFlagPipe} from '@taiga-ui/core';
import {
TUI_IS_APPLE,
TuiInputModule,
TuiTextfieldControllerModule,
} from '@taiga-ui/legacy';
import metadata from 'libphonenumber-js/min/metadata';
import mask from './mask';
@Component({
standalone: true,
selector: 'phone-doc-example-3',
imports: [
FormsModule,
MaskitoDirective,
TuiFlagPipe,
TuiInputModule,
TuiTextfieldControllerModule,
],
template: `
Non-strict
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PhoneMaskDocExample3 {
private readonly isApple = inject(TUI_IS_APPLE);
protected value = '';
protected readonly mask = mask;
protected get countryIsoCode(): string {
return maskitoGetCountryFromNumber(this.value, metadata) ?? '';
}
protected get pattern(): string {
return this.isApple ? '+[0-9-]{1,20}' : '';
}
}
```
--------------------------------
### Initializing Maskito with Shift Mode (JavaScript)
Source: https://maskito.dev/core-concepts/overwrite-mode
Demonstrates how to initialize Maskito with a specific configuration, including the 'shift' overwrite mode, on a DOM element. Includes cleanup.
```javascript
import {Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Vue Integration with v-maskito Directive
Source: https://maskito.dev/addons/phone
Shows how to use Maskito within a Vue.js application with the `v-maskito` directive. This example covers registering the directive and binding Maskito options to an input element in a Vue instance.
```javascript
import {createApp} from 'vue';
import {maskito} from '@maskito/vue';
import options from './mask';
const app = createApp({
template: '',
directives: {maskito},
data: () => ({ options }),
});
```
--------------------------------
### Maskito Number Kit API Documentation
Source: https://maskito.dev/kit/number/API
This section details the configuration options available for the Maskito Number Kit, allowing for customization of decimal separators, thousand separators, precision, and more.
```APIDOC
MaskitoNumberOptions:
decimalSeparator?: string
Symbol for separating fraction. Default: point.
decimalPseudoSeparators?: string[]
Symbols to be replaced with decimalSeparator. Default: ['.', 'ю', 'б'].
thousandSeparator?: string
Symbol for separating thousands. Default: non-breaking space.
minimumFractionDigits?: number
The minimum number of fraction digits to use. Right-pads with zeros if needed. Default: 0.
maximumFractionDigits?: number
The maximum number of digits after decimalSeparator. Use Infinity for untouched decimal part. Default: 0.
min?: number
The lowest permitted value. Default: Number.MIN_SAFE_INTEGER.
max?: number
The greatest permitted value. Default: Number.MAX_SAFE_INTEGER.
prefix?: string
A prefix symbol, like currency. Default: empty string.
postfix?: string
A postfix symbol, like currency. Default: empty string.
minusSign?: string
A minus symbol. Default: '\u2212'.
precision?: number
Deprecated. Use maximumFractionDigits instead! Number of digits after decimalSeparator. Default: 0.
decimalZeroPadding?: boolean
Deprecated. Use minimumFractionDigits instead! If number of digits after decimalSeparator is always equal to the precision. Default: false.
```
--------------------------------
### Angular Input Masking with MaskitoPattern
Source: https://maskito.dev/frameworks/angular
Demonstrates how to apply a regular expression-based mask to an input field in Angular using the MaskitoPattern directive. This example shows masking for a 'Name' field with a regex for letters and spaces, and a 'CVC' field with a regex for digits.
```typescript
import {ChangeDetectionStrategy, Component} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {MaskitoPattern} from '@maskito/angular';
@Component({
standalone: true,
selector: 'pattern-doc-example-6',
imports: [FormsModule, MaskitoPattern],
templateUrl: './template.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PatternDocExample6 {
protected name = '';
protected cvc = '';
protected regExp = /^[a-zA-Z\s]+$/;
}
```
```html
```
--------------------------------
### Maskito Time Kit API Documentation
Source: https://maskito.dev/kit/time/API
This section details the API for the Maskito Time Kit, including available modes, segment value configurations, stepping, prefixes, and postfixes.
```APIDOC
MaskitoTimeMode:
'HH:MM' | 'HH:MM:SS' | 'HH' | 'MM' | 'SS'
MaskitoTimeSegments:
{
hours?: T;
minutes?: T;
seconds?: T;
}
MaskitoTimeOptions:
mode?: MaskitoTimeMode;
timeSegmentMinValues?: MaskitoTimeSegments;
timeSegmentMaxValues?: MaskitoTimeSegments;
step?: number;
prefix?: string;
postfix?: string;
// Example Usage:
// const timeMask = createMask({ ...options });
// Parameters:
// mode: Time format mode. Defaults to 'HH:MM'.
// timeSegmentMinValues: Minimum value for each time segment. Defaults vary based on mode.
// - hours: 0 (for 24-hour mode) or 1 (for 12-hour mode with meridiem)
// timeSegmentMaxValues: Maximum value for each time segment. Defaults vary based on mode.
// - hours: 24 (for 24-hour mode) or 12 (for 12-hour mode with meridiem)
// step: Value to increment/decrement time segments with keyboard arrows. Default is 0 (disabled).
// prefix: Uneditable text before the time. Default is an empty string.
// postfix: Uneditable text after the time. Default is an empty string.
```
--------------------------------
### Initializing Maskito in Vanilla JavaScript
Source: https://maskito.dev/core-concepts/overwrite-mode
Shows how to initialize Maskito on an HTML element using the defined options. It also includes a method to destroy the Maskito instance when the element is removed from the DOM.
```javascript
import {Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### Custom Plugin for Input Formatting on Blur
Source: https://maskito.dev/core-concepts/plugins
Demonstrates creating a custom Maskito plugin that adds a leading zero to the input value if it starts with a decimal point when the element loses focus. It uses `maskitoUpdateElement` for updating the value and event listeners for blur events.
```typescript
import type {
MaskitoElement,
MaskitoOptions,
} from '@maskito/core';
import {maskitoUpdateElement} from '@maskito/core';
export default {
mask: /^\d*\.?\d*$/,
plugins: [
(element: MaskitoElement, _: MaskitoOptions) => {
const blurHandler = (): void => {
if (element.value.startsWith('.')) {
/**
* ❌ Anti-Pattern:
* ```
* element.value = `0${element.value}`;
* ```
*/
maskitoUpdateElement(element, `0${element.value}`);
}
};
element.addEventListener('blur', blurHandler);
// register a clean-up callback that is invoked when the mask is destroyed
return () => element.removeEventListener('blur', blurHandler);
},
],
} satisfies MaskitoOptions;
```
--------------------------------
### HTML Template for Maskito Unmask Handler Example
Source: https://maskito.dev/frameworks/angular
The HTML template for the Angular component. It includes an input element with Maskito applied (`[maskito]`) and a custom unmask handler (`[unmaskHandler]`). The input's value is managed via `[(ngModel)]`, and a button is provided to programmatically change the value.
```html
Control value:{{ value }}
```
--------------------------------
### DateRange Kit API Documentation
Source: https://maskito.dev/kit/date-range/API
This section details the configuration options for the DateRange Kit, including date format modes, separators, and date range constraints.
```apidoc
DateRange Kit Configuration:
- [mode] Date format mode:
- Type: MaskitoDateMode
- Value: 'dd/mm/yyyy' (dd/mm/yyyy)
- [dateSeparator] Separator between date segments (days, months, and years).
- Type: string
- Default: '.' (dot)
- [rangeSeparator] Separator between dates of the date range.
- Type: string
- Default: ' – '
- [min] Earliest date allowed.
- Type: Date
- Value: '0001-01-01'
- [max] Latest date allowed.
- Type: Date
- Value: '9999-12-31'
- [minLength] Minimal length of the range.
- Type: MaskitoDateSegments
- Value: {}
- [maxLength] Maximal length of the range.
- Type: MaskitoDateSegments
- Value: {}
```
--------------------------------
### Angular Component for Dynamic Decimal Zero Padding
Source: https://maskito.dev/kit/number
An Angular component that utilizes Maskito for number input. It dynamically enables decimal zero padding based on user interaction, specifically when a decimal separator is entered. This example showcases integration with Angular's forms and Maskito directives.
```typescript
import {ChangeDetectionStrategy, Component} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {MaskitoDirective} from '@maskito/angular';
import type {MaskitoOptions} from '@maskito/core';
import {tuiPure} from '@taiga-ui/cdk';
import {TuiLabel} from '@taiga-ui/core';
import {TuiInputModule, TuiTextfieldControllerModule} from '@taiga-ui/legacy';
import {getMaskitoOptions} from './mask';
@Component({
standalone: true,
selector: 'number-mask-doc-example-6',
imports: [
FormsModule,
MaskitoDirective,
TuiInputModule,
TuiLabel,
TuiTextfieldControllerModule,
],
template: `
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NumberMaskDocExample6 {
protected value = '42';
protected decimalZeroPadding = this.value.includes('.');
@tuiPure // Decorator for memoization
protected getMaskOptions(decimalZeroPadding: boolean): MaskitoOptions {
return getMaskitoOptions(decimalZeroPadding);
}
protected handleBeforeInput(event: Event): void {
const {inputType, target, data} = event as InputEvent;
if (inputType.includes('delete')) {
const element = target as HTMLInputElement;
const [from, to] = this.getNotEmptySelection(
[element.selectionStart ?? 0, element.selectionEnd ?? 0],
inputType.includes('Forward'),
);
const dotWasRemoved = this.value.slice(from, to).includes('.');
this.decimalZeroPadding = this.decimalZeroPadding && !dotWasRemoved;
} else {
// eslint-disable-next-line i18n/no-russian-character
this.decimalZeroPadding = ['.', ',', 'б', 'ю'].some(
(sep) => data?.includes(sep) || this.value.includes(sep),
);
}
}
private getNotEmptySelection(
[from, to]: [number, number],
isForward: boolean,
): [number, number] {
if (from !== to) {
return [from, to];
}
return isForward ? [from, to + 1] : [Math.max(from - 1, 0), to];
}
}
```
--------------------------------
### Dynamic Mask Expression for Word Count
Source: https://maskito.dev/core-concepts/mask-expression
This example illustrates a dynamic mask expression that limits the number of words allowed in an input field. The mask is generated by a function that creates a RegExp based on a variable `howManyWordsAllowed`. This approach is flexible but requires careful performance consideration due to regeneration on each input change.
```javascript
import { Maskito } from '@maskito/core';
let howManyWordsAllowed = 5;
const maxWordInput = new Maskito(element, {
mask: (elementState) => new RegExp('^(\w+\s?){0,' + howManyWordsAllowed + '}$')
});
```
--------------------------------
### RegExp Mask Expression for Digits
Source: https://maskito.dev/core-concepts/mask-expression
This example demonstrates how to use a regular expression to create a mask that accepts only digits. The mask /^d+$/ ensures that the input consists solely of one or more digits. It's crucial that the RegExp matches intermediate states, so /^d{0,4}$/ is preferred for a 4-digit PIN to allow partial input.
```javascript
import { Maskito } from '@maskito/core';
const onlyDigitsInput = new Maskito(element, {
mask: /^\d+$/,
});
```
--------------------------------
### Pattern Mask Expression for Time (HH:MM)
Source: https://maskito.dev/core-concepts/mask-expression
This example shows a pattern mask expression for a time format (HH:MM). It uses an array where digits are represented by /d/ and the colon ':' is a fixed character. This pattern enforces the format and handles user input, like automatically inserting the colon or managing backspace behavior around it.
```javascript
import { Maskito } from '@maskito/core';
const timeInput = new Maskito(element, {
mask: [/d/, /d/, ':', /d/, /d/],
});
```
--------------------------------
### Maskito Vue Best Practices
Source: https://maskito.dev/frameworks/vue
Illustrates the recommended way to pass Maskito options to the `v-maskito` directive to avoid unnecessary re-creations.
```html
```
--------------------------------
### Vanilla JavaScript Integration
Source: https://maskito.dev/kit/time
Illustrates how to integrate Maskito's time masking into a web page using vanilla JavaScript. It involves creating a Maskito instance for an input element and handling its lifecycle with `destroy()`.
```javascript
import {Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask';
const element = document.querySelector('input,textarea')!;
const maskedInput = new Maskito(element, maskitoOptions);
// Call this function when the element is detached from DOM
maskedInput.destroy();
```
--------------------------------
### React Integration
Source: https://maskito.dev/kit/time
Illustrates integrating Maskito with time stepping in a React application using the `useMaskito` hook. The hook takes the Maskito options and returns a ref to attach to the input element.
```javascript
import * as React from 'react';
import {useMaskito} from '@maskito/react';
import options from './mask';
export default function App(
const maskedInputRef = useMaskito({options});
return ;
}
```
--------------------------------
### Best Practice: Avoid Unnecessary Maskito Recreation
Source: https://maskito.dev/frameworks/react
Illustrates the best practice of passing named variables to Maskito configurations to prevent unnecessary re-creations of the mask instance on re-renders.
```jsx
import React, { useState, useMemo } from 'react';
import { useMaskito } from '@maskito/react';
function OptimizedMaskedInput() {
const [value, setValue] = useState('');
// Memoize the maskito configuration
const maskitoOptions = useMemo(() => ({
mask: /\d/,
onInput: (event) => {
setValue(event.target.value);
},
}), []); // Empty dependency array means this object is created only once
const inputRef = useMaskito(maskitoOptions);
return ;
}
```
--------------------------------
### Preprocessor Action Types
Source: https://maskito.dev/core-concepts/processors
Lists the possible action types that can trigger a preprocessor. These correspond to user input events like insertion or deletion.
```typescript
type ActionType = 'insert' | 'deleteForward' | 'deleteBackward' | 'validation';
```
--------------------------------
### Phone Addon API Documentation
Source: https://maskito.dev/addons/phone/API
API reference for the Maskito phone addon, detailing configuration options for phone number parsing and formatting.
```APIDOC
createPhoneMask(options)
- Creates a Maskito plugin for phone number input.
- Parameters:
- metadata (string): List of phone number parsing and formatting rules. Options: 'max', 'min', 'mobile', 'core'. Defaults to 'min'.
- countryIsoCode (string): Country ISO-code for strict country phone number validation. Defaults to 'RU'.
- strict (boolean): If true, allows only phone numbers of the selected country. Defaults to true.
- separator (string): Separator between groups of numbers (excluding country code and area code). Defaults to '-'.
- Returns: A Maskito plugin function.
```
--------------------------------
### Integrate Maskito Phone Input with React
Source: https://maskito.dev/addons/phone
Demonstrates integrating Maskito phone masking into a React application using the `useMaskito` hook. The hook takes the mask options and returns a ref to be attached to the input element.
```javascript
import * as React from 'react';
import {useMaskito} from '@maskito/react';
import options from './mask';
export default function App(
) {
const maskedInputRef = useMaskito({options});
return ;
}
```
--------------------------------
### Basic Maskito Usage in React
Source: https://maskito.dev/frameworks/react
Demonstrates how to use Maskito in a React component by applying the maskito hook to an input element.
```jsx
import React from 'react';
import { useMaskito } from '@maskito/react';
function MyInput() {
const inputRef = useMaskito({
mask: /\d/,
});
return ;
}
```
--------------------------------
### Maskito Core Functionality
Source: https://maskito.dev/getting-started/what-is-maskito
Maskito's core libraries are built with TypeScript and provide a flexible API for creating input masks. They support various user interactions like typing, deleting, pasting, and browser autofill. The core package is zero-dependency, making it suitable for vanilla JavaScript projects.
```typescript
import Maskito from 'maskito';
// Example usage with an HTML input element
const element = document.getElementById('my-input') as HTMLInputElement;
const maskito = new Maskito(element, {
// Mask configuration options here
});
```
```javascript
import Maskito from 'maskito';
// Example usage with an HTML input element
const element = document.getElementById('my-input');
const maskito = new Maskito(element, {
// Mask configuration options here
});
```
--------------------------------
### Time Parsing and Stringifying
Source: https://maskito.dev/kit/time
Demonstrates how to parse a time string into milliseconds and stringify milliseconds back into a time string using `maskitoParseTime` and `maskitoStringifyTime`. It shows handling of different time formats and partial inputs.
```typescript
import {maskitoParseTime, maskitoStringifyTime, MaskitoTimeParams} from '@maskito/kit';
const params: MaskitoTimeParams = {mode: 'HH:MM:SS.MSS'};
maskitoParseTime('23:59:59.999', params); // 86399999
maskitoParseTime('12:3', params); // 43380000 (parsed like '12:30:00.000')
maskitoStringifyTime(86399999, params); // '23:59:59.999'
```
--------------------------------
### Using Maskito in React
Source: https://maskito.dev/kit/time
Illustrates the integration of Maskito within a React application using the `useMaskito` hook. This hook simplifies the process of applying Maskito to a ref-attached input element.
```javascript
import * as React from 'react';
import {useMaskito} from '@maskito/react';
import options from './mask';
export default function App(
const maskedInputRef = useMaskito({options});
return ;
}
```
--------------------------------
### React Integration with useMaskito Hook
Source: https://maskito.dev/kit/number
Illustrates how to integrate Maskito with React using the `useMaskito` hook to manage the mask on an input element.
```javascript
import * as React from 'react';
import {useMaskito} from '@maskito/react';
import options from './mask';
export default function App(
const maskedInputRef = useMaskito({options});
return ;
}
```
--------------------------------
### React Maskito Integration
Source: https://maskito.dev/kit/number
Illustrates how to use Maskito within a React application with the `useMaskito` hook. This hook attaches the Maskito instance to a provided ref.
```javascript
import * as React from 'react';
import {useMaskito} from '@maskito/react';
import options from './mask';
export default function App(
) {
const maskedInputRef = useMaskito({options});
return ;
}
```
--------------------------------
### React Maskito Integration
Source: https://maskito.dev/kit/time
Illustrates integrating Maskito with a React application using the useMaskito hook. This hook takes MaskitoOptions and applies the mask to a referenced input element.
```javascript
import * as React from 'react';
import {useMaskito} from '@maskito/react';
import options from './mask';
export default function App(
const maskedInputRef = useMaskito({options});
return ;
}
```
--------------------------------
### Merging Maskito Ref with Third-Party Refs
Source: https://maskito.dev/frameworks/react
Illustrates how to use React's ref callback pattern to combine the Maskito ref with other refs, such as those from third-party libraries.
```jsx
import React, { useRef } from 'react';
import { useMaskito } from '@maskito/react';
function MergedRefsInput() {
const externalRef = useRef(null);
const maskitoRef = useMaskito({
mask: /\d/,
});
const combinedRef = (el) => {
// Call both refs
maskitoRef(el);
if (externalRef.current) {
externalRef.current = el;
}
};
return ;
}
```
--------------------------------
### Maskito Initialization in TypeScript
Source: https://maskito.dev/stackblitz
Initializes Maskito with custom options on an HTML input element. It defines a mask to accept only digits and logs the destroy method for potential cleanup.
```typescript
import './styles.css';
import type {MaskitoOptions} from '@maskito/core';
import {Maskito} from '@maskito/core';
const maskitoOptions: MaskitoOptions = {
mask: /\d+$/,
};
const input: HTMLInputElement | null = document.querySelector
('input');
if (input) {
const maskedInput = new Maskito(input, maskitoOptions);
console.info(
'Call this function when the element is detached
from DOM',
maskedInput.destroy,
);
}
```