react-input-mask vs react-maskedinput vs react-number-format vs react-phone-number-input vs react-text-mask
Input Masking Libraries for React
react-input-maskreact-maskedinputreact-number-formatreact-phone-number-inputreact-text-maskSimilar Packages:

Input Masking Libraries for React

Input masking libraries are essential tools in web development that help format user input in real-time, ensuring that data is entered in a specific format. These libraries enhance user experience by providing visual cues and preventing errors, especially for fields that require specific formats such as phone numbers, dates, or numerical values. Each of these libraries offers unique features and functionalities tailored to different use cases, making it crucial for developers to choose the right one based on their project requirements.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-input-mask02,289-1398 years agoMIT
react-maskedinput0729-628 years agoMIT
react-number-format04,086244 kB22718 days agoMIT
react-phone-number-input0-10.1 MB-a month agoMIT
react-text-mask08,22748.8 kB333-Unlicense

Feature Comparison: react-input-mask vs react-maskedinput vs react-number-format vs react-phone-number-input vs react-text-mask

Customization

  • react-input-mask:

    react-input-mask offers extensive customization options, allowing developers to define dynamic masks based on user input. This flexibility makes it suitable for a wide range of applications requiring specific formatting.

  • react-maskedinput:

    react-maskedinput provides basic customization features, but it is more limited compared to other libraries. It is best for straightforward use cases where advanced customization is not necessary.

  • react-number-format:

    react-number-format allows for customization of number formats, including currency and percentage formats. Developers can easily define how numbers should be displayed, making it ideal for financial applications.

  • react-phone-number-input:

    react-phone-number-input supports customization for international phone number formats, allowing developers to specify the desired format and validation rules based on country codes.

  • react-text-mask:

    react-text-mask is highly customizable, enabling developers to create complex masks that can adapt to different input scenarios. This makes it suitable for applications requiring unique formatting.

Validation

  • react-input-mask:

    react-input-mask includes built-in validation to ensure that user input adheres to the specified mask. This feature helps prevent errors and improves data integrity.

  • react-maskedinput:

    react-maskedinput provides basic validation capabilities, ensuring that the input matches the defined mask. However, it may not offer advanced validation features found in other libraries.

  • react-number-format:

    react-number-format includes validation for numerical inputs, ensuring that only valid numbers are accepted. This is particularly useful for applications that require strict number formatting.

  • react-phone-number-input:

    react-phone-number-input offers robust validation for phone numbers, checking that the input conforms to international formats and providing feedback to users if the input is invalid.

  • react-text-mask:

    react-text-mask allows for validation based on the defined mask, ensuring that user input matches the expected format. This helps maintain data integrity.

Performance

  • react-input-mask:

    react-input-mask is optimized for performance, making it suitable for applications with high input frequency and complex masking requirements. It efficiently handles user input without significant lag.

  • react-maskedinput:

    react-maskedinput is lightweight and designed for performance, making it a good choice for applications where speed is essential and minimal overhead is desired.

  • react-number-format:

    react-number-format is optimized for handling numerical inputs efficiently, ensuring that formatting does not hinder performance, especially in applications with frequent updates.

  • react-phone-number-input:

    react-phone-number-input is designed for performance, providing a smooth user experience even when validating international phone numbers. It minimizes lag during input.

  • react-text-mask:

    react-text-mask is efficient in handling complex masks, ensuring that performance remains high even with intricate input requirements.

Ease of Use

  • react-input-mask:

    react-input-mask is user-friendly, with a straightforward API that makes it easy for developers to implement and customize input masks without extensive configuration.

  • react-maskedinput:

    react-maskedinput is simple to use, making it ideal for developers looking for a quick solution without the need for complex setup or configuration.

  • react-number-format:

    react-number-format is easy to integrate and use, providing clear documentation and examples that help developers implement number formatting quickly.

  • react-phone-number-input:

    react-phone-number-input is designed with user experience in mind, offering an intuitive interface for entering phone numbers, which enhances usability.

  • react-text-mask:

    react-text-mask is relatively easy to use, but its advanced customization options may require a bit more time to fully understand and implement.

Community Support

  • react-input-mask:

    react-input-mask has a strong community and active maintenance, ensuring that developers can find support and updates easily.

  • react-maskedinput:

    react-maskedinput has a smaller community, which may limit the availability of resources and support compared to more popular libraries.

  • react-number-format:

    react-number-format benefits from a robust community and extensive documentation, making it easy for developers to find help and examples.

  • react-phone-number-input:

    react-phone-number-input has a growing community, providing support and resources for developers implementing international phone number formats.

  • react-text-mask:

    react-text-mask has a solid community backing, with plenty of resources available for troubleshooting and implementation guidance.

How to Choose: react-input-mask vs react-maskedinput vs react-number-format vs react-phone-number-input vs react-text-mask

  • react-input-mask:

    Choose react-input-mask if you need a flexible and customizable input masking solution that allows for dynamic masks and supports various input types. It is ideal for applications that require specific formatting for inputs like dates or credit card numbers.

  • react-maskedinput:

    Select react-maskedinput for a straightforward and lightweight option that provides basic input masking capabilities. It is suitable for simpler applications where minimal configuration is needed and where performance is a priority.

  • react-number-format:

    Opt for react-number-format when you need to handle numerical inputs with formatting options such as currency, percentages, or custom number formats. This library is particularly useful for financial applications where precise number formatting is crucial.

  • react-phone-number-input:

    Use react-phone-number-input if your application requires international phone number input with validation. This library provides a user-friendly interface for entering phone numbers and ensures that the input conforms to international standards.

  • react-text-mask:

    Choose react-text-mask for a highly customizable input masking solution that allows for complex masks and supports various input types. It is ideal for applications that require advanced formatting options and flexibility in user input.

README for react-input-mask

react-input-mask

Build Status npm version npm downloads

Input masking component for React. Made with attention to UX. Compatible with IE8+.

Demo

Table of Contents

Install

npm install react-input-mask --save

Also you can use it without a module bundler

<!-- Load React first -->
<script src="https://unpkg.com/react/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom/dist/react-dom.min.js"></script>
<!-- Will be exported to window.ReactInputMask -->
<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:

  1. 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 } }
  2. 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.
  3. 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).
  4. 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] // permanents is an array of indexes of the non-editable characters in the mask
}

beforeMaskedValueChange must return an object with following fields:

  1. value (string): New value.
  2. 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';

// Will work fine
const Input = (props) => (
  <InputMask mask="99/99/9999" value={props.value} onChange={props.onChange}>
    {(inputProps) => <MaterialInput {...inputProps} type="tel" disableUnderline />}
  </InputMask>
);

// Will throw an error because InputMask's and children's onChange aren't the same
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;

    // keep minus if entered by user
    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:

  1. Set maskChar to null and trim space after "+1" with beforeMaskedValueChange if no more digits are entered.
  2. 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.
  3. 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