react-native-mask-input

repository·main·Indexed 43 days ago

https://github.com/caioquirinomedeiros/react-native-mask-input

A TextInput wrapper for React Native (iOS, Android, and Web) providing customizable masking capabilities. Version 1.2.3 features support for RegExp-based patterns, dynamic masks via functions, character obfuscation, and a `useMaskedInputProps` hook for integration with other input components. Includes utilities like `createNumberMask` for currency/numeric formatting and `formatWithMask` for manual string formatting.

Tokens
4.8K
Snippets
18
Records
22
Agent score
49%

What's inside react-native-mask-input

  1. Define a Mask

    main

    A mask is an array where each item defines one character of the value.

    • Use a string for static characters (e.g., '-', ' ', '(').
    • Use a RegExp for characters that the user inputs (e.g., /\d/ for digits).

    Note: All characters intended to be input by the user must be a RegExp in your mask array.

    const zipCodeMask = [/\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/];
  2. Define a Mask type

    main

    A Mask is a collection of MaskItems that define how text should be formatted. A Mask can be represented in two ways:

    1. A MaskArray: An array of MaskItems where each item is a string, a RegExp, or a tuple containing a RegExp (e.g., [RegExp]).
    2. A function: A function that accepts an optional value string and returns a MaskArray.
    // Example of a MaskArray
    const mask: Mask = ['9', '9', '/', '9', '9'];
    
    // Example of a function mask
    const dynamicMask: Mask = (value) => {
      if (value?.length > 2) return ['9', '9', '9'];
      return ['9', '9'];
    };
  3. Use the MaskInput component

    main

    The MaskInput component is a wrapper around the standard React Native TextInput. It requires a value and an onChangeText callback. The mask prop defines the input pattern using an array of strings (for static characters) and RegExp (for character validation).

    import MaskInput from 'react-native-mask-input';
    
    function MyComponent() {
      const [phone, setPhone] = React.useState('');
    
      return (
        <MaskInput
          value={phone}
          onChangeText={(masked, unmasked) => {
            setPhone(masked); 
            // masked: (99) 99999-9999
            // unmasked: 99999999999
          }}
          mask={['(', /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
        />
      );
    }
  4. Use a function mask for dynamic masking

    main

    The mask prop can accept a function instead of an array. This function receives the current text as an argument and should return a Mask array. This is useful for switching masks dynamically based on the input length or content (e.g., switching between CPF and CNPJ masks).

    const CPF_MASK = [/\d/, /\d/, /\d/, ".", /\d/, /\d/, /\d/, ".", /\d/, /\d/, /\d/, "-", /\d/, /\d/];
    const CNPJ_MASK = [/[a-zA-Z0-9]/, /[a-zA-Z0-9]/, ".", /[a-zA-Z0-9]/, /[a-zA-Z0-9]/, ".", /[a-zA-Z0-9]/, "/", /[a-zA-Z0-9]/, /[a-zA-Z0-9]/, /[a-zA-Z0-9]/, "-", /\d/, /\d/];
    
    // Inside component:
    <MaskInput
      value={value}
      onChangeText={setValue}
      mask={(text) => {
        if (text.replace(/\D+/g, "").length <= 11) {
          return CPF_MASK;
        } else {
          return CNPJ_MASK;
        }
      }}
    />
  5. Obfuscate characters in a mask

    main

    To obfuscate specific characters (e.g., for credit card numbers), wrap the RegExp in an array within the mask definition. You must also set the showObfuscatedValue prop to true to see the effect in the UI.

    // Wrapping a RegExp in an array marks it for obfuscation
    const creditCardMask = [/\d/, /\d/, /\d/, /\d/, " ", [/\d/], [/\d/], [/\d/], [/\d/], " ", [/\d/], [/\d/], [/\d/], [/\d/], " ", /\d/, /\d/, /\d/, /\d/];
    
    <MaskInput
      value={creditCard}
      mask={creditCardMask}
      showObfuscatedValue
      obfuscationCharacter="#"
      onChangeText={(masked, unmasked, obfuscated) => {
        // masked: "1234 1234 1234 1234"
        // unmasked: "1234123412341234"
        // obfuscated: "1234 #### #### 1234"
      }}
    />
  6. Format text with `formatWithMask(options)`

    main

    Use formatWithMask to manually apply a mask to a string and retrieve the masked, unmasked, and obfuscated versions of that string. This is useful for utility-based formatting outside of a component lifecycle.

    Options

    NameTypeDefaultDescription
    textstringThe text to be formatted.
    maskMaskAn array where each item defines one character of the value. Strings are used as literals; RegExp objects are used for validation.
    obfuscationCharacterstring*The character used to replace characters in the obfuscated output.
    import { formatWithMask, Masks } from 'react-native-mask-input';
    
    const creditCard = '9999999999999999';
    
    const { masked, unmasked, obfuscated } = formatWithMask({
      text: creditCard,
      mask: Masks.CREDIT_CARD,
      obfuscationCharacter: '-',
    });
    
    console.log(masked); // 9999 9999 9999 9999
    console.log(unmasked); // 9999999999999999
    console.log(obfuscated); // 9999 ---- ---- 9999
  7. Apply mask props to an input with `useMaskedInputProps(props)`

    main

    The useMaskedInputProps hook generates a set of props that can be spread onto any React Native input component (like TextInput or third-party components like native-base's Input) to enable masked input behavior.

    Pass an object containing the input's value, onChangeText handler, and the desired mask to the hook. The returned object contains the necessary props to synchronize the masked display with your state.

    import { Input } from 'native-base'
    import { Masks, useMaskedInputProps } from 'react-native-mask-input';
    
    function MyComponent() {
      const [phone, setPhone] = React.useState('');
    
      const maskedInputProps = useMaskedInputProps({
        value: phone,
        onChangeText: setPhone,
        mask: Masks.BRL_PHONE,
      });
    
      return <Input {...maskedInputProps} />
    }
  8. Format text with a mask using formatWithMask()

    main

    The formatWithMask function allows you to manually apply a mask to a string outside of a component. It returns an object containing the masked, unmasked, and obfuscated versions of the text.

    import { formatWithMask } from 'react-native-mask-input';
    
    const zipCodeMask = [/\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/];
    
    const { masked, unmasked, obfuscated } = formatWithMask({
      text: '71680345',
      mask: zipCodeMask,
    });
    
    console.log(masked); // "71680-345"
    console.log(unmasked); // "71680345"
    console.log(obfuscated); // "71680-345"
  9. Create a number mask with createNumberMask()

    main

    Use createNumberMask(numberOptions) to generate a mask for numeric inputs like currency. This is highly useful for handling delimiters, separators, and precision.

    ```js
    import MaskInput, { createNumberMask } from 'react-native-mask-input';
    
    const dollarMask = createNumberMask({
      prefix: ['R', '$', ' '],
      delimiter: '.',
      separator: ',',
      precision: 2,
    });
    
    <MaskInput
      value={value}
      mask={dollarMask}
      onChangeText={(masked, unmasked) => {
        // masked: "R$ 1.234,56"
        // unmasked: "123456"
      }}
    />

    numberOptions configuration:

    NameTypeDefaultDescription
    prefixMask[]Mask to be prefixed on the mask result.
    delimiterstring.Character for thousands delimiter.
    separatorstring,Decimal separator character.
    precisionnumber2Decimal precision.
  10. Configure UseMaskedInputProps

    main

    The UseMaskedInputProps type defines the configuration options for the useMaskedInputProps hook. This hook is used to provide masking logic and event handlers to a React Native TextInput.

    Available Props:

    • value (string, optional): The current value of the input.
    • mask (Mask, optional): The mask configuration to apply to the input.
    • onChangeText (function, optional): A callback triggered when the text changes. It receives three arguments:
      • masked: The text including mask characters (e.g., 12/12/1990).
      • unmasked: The raw text without mask characters (e.g., 12121990).
      • obfuscated: The text with characters replaced by the obfuscationCharacter (e.g., ****).
    • showObfuscatedValue (boolean, optional): If true, the TextInput will display the obfuscated version of the text. Defaults to false.
    • placeholderFillCharacter (string, optional): The character used to fill the mask in the placeholder.
    • obfuscationCharacter (string, optional): The character used to hide sensitive input (e.g., *). Defaults to *.
    • maskAutoComplete (boolean, optional): If true, automatically appends the next expected mask characters to the end of the value. For example, in a date mask, `
  11. MaskInput Props Reference

    main

    The MaskInput component inherits all props from the standard React Native TextInput. In addition, it provides the following specific props:

    PropTypeDefaultDescription
    valuenumberThe value for controlled input. REQUIRED
    onChangeTextfunctionCallback receiving (maskedText, unmaskedText, obfuscatedText) => void. REQUIRED
    maskMaskArray defining characters. Strings are literal; RegExp validates input.
    showObfuscatedValuebooleanfalseWhether to display the obfuscated value on the TextInput.
    placeholderFillCharacterstring_Character used as the "fill character" on the default placeholder.
    obfuscationCharacterstring*Character used for obfuscated characters.
    maskAutoCompletebooleanfalseAdds next mask characters at the end of the value.