What is react-input-mask?
The react-input-mask package is a versatile input masking library for React applications. It allows developers to create input fields with predefined formats, ensuring that users enter data in a consistent and expected manner. This is particularly useful for fields like phone numbers, dates, and credit card numbers.
What are react-input-mask's main functionalities?
Basic Input Masking
This feature allows you to create a basic input mask for phone numbers. The mask prop defines the format, and the input field will automatically enforce this format as the user types.
import React from 'react';
import InputMask from 'react-input-mask';
function PhoneInput() {
return (
<InputMask mask="(999) 999-9999" placeholder="Enter phone number" />
);
}
export default PhoneInput;
Custom Masking Characters
This feature allows you to define custom masking characters. In this example, the mask includes both numbers and letters, and the maskChar prop specifies the character to use for unfilled positions.
import React from 'react';
import InputMask from 'react-input-mask';
function CustomMaskInput() {
return (
<InputMask mask="99-aaa-9999" maskChar="_" placeholder="Enter custom format" />
);
}
export default CustomMaskInput;
Masking with Validation
This feature demonstrates how to use input masking with state management and validation. The input field is masked for a credit card number, and the value is managed using React's useState hook.
import React, { useState } from 'react';
import InputMask from 'react-input-mask';
function ValidatedInput() {
const [value, setValue] = useState('');
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<InputMask mask="9999-9999-9999-9999" value={value} onChange={handleChange} placeholder="Enter credit card number" />
);
}
export default ValidatedInput;
Other packages similar to react-input-mask
react-text-mask
react-text-mask is another popular library for input masking in React. It offers similar functionality to react-input-mask but also supports masking for other frameworks like Angular and Vue. It provides a flexible API and supports custom mask definitions.
cleave.js
cleave.js is a JavaScript library for formatting input fields. It supports a wide range of input types, including credit cards, phone numbers, and dates. Unlike react-input-mask, cleave.js is not limited to React and can be used with vanilla JavaScript or other frameworks.
imaskjs
imaskjs is a versatile input masking library that supports a wide range of input types and custom masks. It offers a rich set of features, including dynamic masks and pattern matching. imaskjs can be used with React, Angular, Vue, and vanilla JavaScript.
react-input-mask
Input masking component for React. Made with attention to UX. Compatible with IE8+.
Table of Contents
Install
npm install react-input-mask --save
Also you can use it without a module bundler
<script src="https://unpkg.com/react/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom/dist/react-dom.min.js"></script>
<script src="https://unpkg.com/react-input-mask/dist/react-input-mask.min.js"></script>
Properties
mask
: string
Mask string. Default format characters are:
9
: 0-9
a
: A-Z, a-z
*
: A-Z, a-z, 0-9
Any character can be escaped with a backslash. It will appear as a double backslash in JS strings. For example, a German phone mask with unremoveable prefix +49 will look like mask="+4\9 99 999 99"
or mask={'+4\\9 99 999 99'}
maskChar
: string
Character to cover unfilled parts of the mask. Default character is "_". If set to null or empty string, unfilled parts will be empty as in ordinary input.
formatChars
: object
Defines format characters with characters as a keys and corresponding RegExp strings as a values. Default ones:
{
'9': '[0-9]',
'a': '[A-Za-z]',
'*': '[A-Za-z0-9]'
}
alwaysShowMask
: boolean
Show mask when input is empty and has no focus.
inputRef
: function
Use inputRef
instead of ref
if you need input node to manage focus, selection, etc.
Experimental :fire:
The following props are considered experimental because they are more prone to issues and are likely to be changed in the future. Use with caution.
beforeMaskedValueChange
: function
In case you need to implement more complex masking behavior, you can provide beforeMaskedValueChange
function to change masked value and cursor position before it will be applied to the input. beforeMaskedValueChange
receives following arguments:
- newState (object): New input state. Contains
value
and selection
fields. selection
is null on input blur or when function is called before input mount. Example: { value: '12/1_/____', selection: { start: 4, end: 4 } }
- oldState (object): Input state before change. Contains
value
and selection
fields. selection
is null on input focus or when function is called before input mount. - userInput (string): Raw entered or pasted string.
null
if user didn't enter anything (e.g. triggered by deletion or rerender due to props change). - maskOptions (object): Mask options. Example:
{
mask: '99/99/9999',
maskChar: '_',
alwaysShowMask: false,
formatChars: {
'9': '[0-9]',
'a': '[A-Za-z]',
'*': '[A-Za-z0-9]'
},
permanents: [2, 5]
}
beforeMaskedValueChange
must return an object with following fields:
- value (string): New value.
- selection (object): New selection. If
selection
in newState
argument is null, it must be null too.
Please note that beforeMaskedValueChange
executes more often than onChange
and must be pure.
children
: function
NOTE: To make this feature more reliable, please tell about your use case in this issue
To use another component instead of regular <input />
pass render function as a children. Function receives props
argument which contains props that aren't used by react-input-mask's internals. I.e. it passes down every prop except the following ones: onChange
, onPaste
, onMouseDown
, onFocus
, onBlur
, value
, disabled
, readOnly
. These properties, if used, should always be passed directly to react-input-mask instead of children and shouldn't be altered in chldren's function.
import React from 'react';
import InputMask from 'react-input-mask';
import MaterialInput from '@material-ui/core/Input';
const Input = (props) => (
<InputMask mask="99/99/9999" value={props.value} onChange={props.onChange}>
{(inputProps) => <MaterialInput {...inputProps} type="tel" disableUnderline />}
</InputMask>
);
const InvalidInput = (props) => (
<InputMask mask="99/99/9999" value={props.value}>
{(inputProps) => <MaterialInput {...inputProps} type="tel" disableUnderline onChange={props.onChange} />}
</InputMask>
);
Examples
import React from 'react';
import InputMask from 'react-input-mask';
class PhoneInput extends React.Component {
render() {
return <InputMask {...this.props} mask="+4\9 99 999 99" maskChar=" " />;
}
}
Mask for ZIP Code. Uses beforeMaskedValueChange to omit trailing minus if it wasn't entered by user:
import React from 'react';
import InputMask from 'react-input-mask';
class Input extends React.Component {
state = {
value: ''
}
onChange = (event) => {
this.setState({
value: event.target.value
});
}
beforeMaskedValueChange = (newState, oldState, userInput) => {
var { value } = newState;
var selection = newState.selection;
var cursorPosition = selection ? selection.start : null;
if (value.endsWith('-') && userInput !== '-' && !this.state.value.endsWith('-')) {
if (cursorPosition === value.length) {
cursorPosition--;
selection = { start: cursorPosition, end: cursorPosition };
}
value = value.slice(0, -1);
}
return {
value,
selection
};
}
render() {
return <InputMask mask="99999-9999" maskChar={null} value={this.state.value} onChange={this.onChange} beforeMaskedValueChange={this.beforeMaskedValueChange} />;
}
}
Known Issues
Autofill
Browser's autofill requires either empty value in input or value which exactly matches beginning of the autofilled value. I.e. autofilled value "+1 (555) 123-4567" will work with "+1" or "+1 (5", but won't work with "+1 (___) ___-____" or "1 (555)". There are several possible solutions:
- Set
maskChar
to null and trim space after "+1" with beforeMaskedValueChange
if no more digits are entered. - Apply mask only if value is not empty. In general, this is the most reliable solution because we can't be sure about formatting in autofilled value.
- Use less formatting in the mask.
Please note that it might lead to worse user experience (should I enter +1 if input is empty?). You should choose what's more important to your users — smooth typing experience or autofill. Phone and ZIP code inputs are very likely to be autofilled and it's a good idea to care about it, while security confirmation code in two-factor authorization shouldn't care about autofill at all.
Thanks
Thanks to BrowserStack for the help with testing on real devices