0

I'm a beginner with ReactJS and I'm trying to set up a mask for the input field of my form.

This mask that I'm trying to configure must be dynamic, because it should work if the field is CPF or CPNJ:

CPF format: 111.111.111-11

CNPJ format: 11.111.111/1111-11

Regex to validate both: /(^\d{3}\.\d{3}\.\d{3}\-\d{2}$)|(^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$)/

I am using react-text-mask to try to configure the mask. I am inserting the CPF and CNPJ regex but the react-text-mask does not recognize it. When the user types more than 11 characters automatically, the mask is in the CNPJ format. Can you tell me how I can do that?

Here's my code I put into codesandbox

Thanks in advance.

1 Answer 1

1

You can simply format the data in the input event using the onChange property of the TextField component and then remove the InputProps property and the TextMaskCustom component.

const handleCpfCnpjChange = (event) => {
  // Get only the numbers from the data input
  let data = event.target.value.replace(/\D/g, "");
  // Checking data length to define if it is cpf or cnpj
  if (data.length > 11) {
    // It's cnpj
    let cnpj = `${data.substr(0, 2)}.${data.substr(2,3)}.${data.substr(5,3)}/`;
    if (data.length > 12)
      cnpj += `${data.substr(8, 4)}-${data.substr(12, 2)}`;
    else 
      cnpj += data.substr(8);
    // Pass formatting for the data
    data = cnpj;
  } else {
    // It's cpf
    let cpf = "";
    let parts = Math.ceil(data.length / 3);
    for (let i = 0; i < parts; i++) {
      if (i === 3) {
        cpf += `-${data.substr(i * 3)}`;
        break;
      }
      cpf += `${i !== 0 ? "." : ""}${data.substr(i * 3, 3)}`;
    }
    // Pass formatting for the data
    data = cpf;
  }
  // Update state
  setcpfCnpjValue(data);
};

Complete code here: codesandbox

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.