function mask(selector, mask, regex) {
if (regex) {
document.querySelector(selector).setAttribute('pattern', regex);
}
document.querySelector(selector)
.addEventListener('keypress', () => {
const text = document.querySelector(selector);
addValue(mask, text.value.length, text);
});
function addValue(origin, now, input) {
if (origin[now] && origin[now] !== '0') {
input.value += origin[now];
if (origin[now +1] && origin[now +1] !== '0') {
addValue(origin, now +1, input);
}
}
}
}
- selector (obrigatório): ID ou classe do elemento a ser editado;
- mask (obrigatório): Padrão desejado para a edição, usando como base números zeros (0);
- regex (opcional): Expressão Regular para ser adicionada ao pattern
Observação: Se você for passar a regex como parâmetro, lembra passa-lá como string e de duplicar as/
para que a sua string não fique "deformada".
<body>
<label>
<p>CPF:</p>
<input type="text" name="cpf" id="cpf" placeholder="Digite seu telefone (00) 00000-0000" required>
</label>
</body>
<script>
// cole a função aqui
// // selector mask regex (com as `/` duplicadas e em formato string)
mask('#cpf', '000.000.000-00', '[0-9]{3}\\.[0-9]{3}\\.[0-9]{3}-[0- 9]{2}');
</script>
<body>
<label>
<p>Telefone:</p>
<input type="text" name="telefone" class="telefone" id="telefone" placeholder="Digite seu telefone (00) 00000-0000" required>
</label>
</body>
<script>
// cole a função aqui
// selector mask
mask('.telefone', '(00)00000-0000');
</script>
Nos dois casos eu digitei apenas os números
- selector (mandatory): ID or class of the element to be edited;
- mask (mandatory): Desired pattern for editing, using zeros (0) as a base;
- regex (optional): Regular expression to be added to the pattern
Note: If you are going to pass the regex as a parameter, remember to pass it as a string and to double the/
so that your string is not "deformed".
<body>
<label>
<p>CPF:</p>
<input type="text" name="cpf" id="cpf" placeholder="Digite seu telefone (00) 00000-0000" required>
</label>
</body>
<script>
// pastle the function here
// mask regex selector (with duplicate `/` and in string format)
mask('#cpf', '000.000.000-00', '[0-9]{3}\\.[0-9]{3}\\.[0-9]{3}-[0- 9]{2}');
</script>
<body>
<label>
<p>Telefone:</p>
<input type="text" name="phone" class="phone" id="phone" placeholder="Digite seu telefone (00) 00000-0000" required>
</label>
</body>
<script>
// pastle the function here
// mask selector
mask('.phone', '(00)00000-0000');
</script>
In both cases I just typed the numbers
Felipe Fuckner Clariano
Entre em contato! 💌