DEV Community

vavilov2212
vavilov2212

Posted on

Masked input & text

There are a bunch of options of how to achieve masked inputs and text representation in general.

I’m going to focus on react implementations here.


react-masked-input

The one, that i used lately is react-masked-input

One of the killer features if, that this library exposes simple function, to mask not just input, but any string or value.

import {
  mask,
  createDynamicNumberMaskGenerator,
  createDefaultMaskGenerator,
  createMaskGenerator,
} from 'react-hook-mask';

// ...

mask(
  myValue,
  createDefaultMaskGenerator('+99 (999) 999 99 99')
)}

// or with dynamic mask

mask(
  myValue,
  createDynamicNumberMaskGenerator(
    '+9 (999) 999 99 99',
    '+99 (999) 999 99 99',
    '+999 (999) 999 99 99'
  )
)
Enter fullscreen mode Exit fullscreen mode

The result is:

Masked phone number representation

Add customisation:

import {
  mask,
  createMaskGenerator,
} from 'react-hook-mask';

const MY_RULES = new Map([
    ['C', /[A-Za-z]/],
    ['N', /\d/],
]);

const createMaskGenerator = (mask) => ({
  rules: MY_RULES,
  generateMask: (value) => {
    if (value.length < 12) return mask;

    mask.set('C', '/\+/');
    return mask;
  },
  transform: (v) => v?.toUpperCase(), // and you can conveniently add transformations
});

//...

mask(myValue, createMaskGenerator())
Enter fullscreen mode Exit fullscreen mode

It has even more, like

  • getting expected cursor position,
  • unmask,
  • 4 types of hook for any needs.

Pretty neat, but underrated, only 22 stars on github.


react-rxinput

💡 It has a Demo page

The other one, that’s interesting is react-rxinput.

It operates on the same principle of handling mask pattern as regular expression (which is cool). As to working with input element it uses RXInputMask which does all the heavy lifting.

RXInputMask comes from incr-regex-package - a module to handle regular expression validation in steps instead of all at once.

I haven't utilised it in any of my projects due to lack of ongoing development, but it's nice to experiment with the concept and draw inspiration from it.


react-phone-input-2

react-phone-input-2 has more of a narrowly focused approach. But i did use it at my job on a project that needed just this functionality.

It’s basically this:

Demo of rendered inputs

💡 The set of countries is predefined as array in a separate file, and was last updated in 2021.

The library gives you an opportunity to

  • filter out only countries, that you actually need,
  • apply custom sorting,
  • add localisation (on top of predefined ones),
  • add custom masks,
  • etc.

Others

There are other packages, which have more stars, like react-input-mask or react-maskedinput. They are both great libraries, which achieve what they aim for.

That’s it, thanks for reading!

Top comments (0)