How to make a Mask input that has more than one mask possible?

Asked

Viewed 264 times

-1

I am making a form and using the React-input-Mask component. I am in the phone field part, and would like to accept either the '(99) 9999-9999' or '(99) 9 9999-9999' landline format, but after reading the documentation I could not figure out how to do this.

<InputMask onBlur={(e) => this.handleBlur('telefone', e.target.value)}
           type="text"
           defaultValue={new_item.telefone}                        
           class='inputTextCriar'
           mask="(99) 9999-9999">
</InputMask>

This is the code at the moment, I would like to make this same field accept both formats. I thank you already!

1 answer

1


I found this solution as an external component

import React, { useState } from 'react';
import InputMask from 'react-input-mask';

const PhoneInput = ({ className, ...props }) => {
  const [mask, setMask] = useState("(99) 99999-9999");

  return (
    <InputMask
      {...props}
      mask={mask}
      onBlur={e => {
        if (e.target.value.replace("_", "").length === 14) {
          setMask("(99) 9999-9999");
        }
      }}
      onFocus={e => {
        if (e.target.value.replace("_", "").length === 14) {
          setMask("(99) 99999-9999");
        }
      }}
    >
      {inputProps => <input {...inputProps} type="tel" />}
    </InputMask>
  );
};

export default PhoneInput;

I believe that if you create this component and import it will work

  • 1

    Good brother! it worked, only if I put the fixed number format it only 'adapts' when I leave the field, but it’s locked. Thanks!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.