2
respostas

Masccara de CPF e telefone

Preciso fazer uma mascara para CPF e Telefone dentro o componente input, quero saber como fazer na mão, sem instalar biblioteca, como se faz?

2 respostas

Em programação, criar uma máscara para CPF e telefone em um componente de input pode ser feito utilizando JavaScript para manipular os eventos do teclado e formatar o valor conforme necessário. Abaixo estão exemplos simples de como você pode implementar isso.

Máscara para CPF:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CPF Mask</title>
</head>
<body>

  <label for="cpf">CPF:</label>
  <input type="text" id="cpf" maxlength="14">

  <script>
    document.getElementById('cpf').addEventListener('input', function (event) {
      let inputValue = event.target.value.replace(/\D/g, ''); // Remove caracteres não numéricos
      inputValue = inputValue.substring(0, 11); // Limita a 11 caracteres (9 dígitos + 2 pontos)

      if (inputValue.length > 9) {
        inputValue = inputValue.replace(/(\d{3})(\d{3})(\d{3})/, '$1.$2.$3-');
      } else if (inputValue.length > 6) {
        inputValue = inputValue.replace(/(\d{3})(\d{3})/, '$1.$2.');
      } else if (inputValue.length > 3) {
        inputValue = inputValue.replace(/(\d{3})/, '$1.');
      }

      event.target.value = inputValue;
    });
  </script>

</body>
</html>

Máscara para Telefone:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Phone Number Mask</title>
</head>
<body>

  <label for="phone">Telefone:</label>
  <input type="text" id="phone" maxlength="14">

  <script>
    document.getElementById('phone').addEventListener('input', function (event) {
      let inputValue = event.target.value.replace(/\D/g, ''); // Remove caracteres não numéricos
      inputValue = inputValue.substring(0, 11); // Limita a 11 caracteres (9 dígitos + 2 pontos)

      if (inputValue.length > 10) {
        inputValue = inputValue.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
      } else if (inputValue.length > 6) {
        inputValue = inputValue.replace(/(\d{2})(\d{4})(\d{0,4})/, '($1) $2-$3');
      } else if (inputValue.length > 2) {
        inputValue = inputValue.replace(/(\d{2})(\d{0,5})/, '($1) $2');
      }

      event.target.value = inputValue;
    });
  </script>

</body>
</html>

Esses exemplos usam o método addEventListener para capturar o evento de input no campo de entrada e aplicam a formatação conforme o usuário digita. A função replace é usada para adicionar os caracteres de pontuação nos lugares apropriados.

Caso tenha conseguido esclarecer suas dúvidas, fico feliz em ter ajudado. Estou à disposição para qualquer outra questão que possa surgir. Um abraço! Se este post foi útil, por favor, marque como solucionado ✓. Desejo a você excelentes estudos!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software