Skip to content
Advertisement

How to make a number mask using only JavaScript?

good evening. I wanna create a mask for my JavaScript project, using only Pure JavaScript, without any jQuery stuff or anything like that. What a want to do is, while I’m writing a bunch of numbers, they will be placed in certain spots. Like, for the final format, I want to do “XXX.XXX.XXX-XX”, but, while writing, “XXX.” and then “XXX.XXX.”, like that. Right now, my code is:

const naosei = document.getElementById('ehistoai');

naosei.addEventListener(onfocus, validarCPF)

function validarCPF(){
    var cpf = naosei.value;

    if (cpf.length === 3){
        cpf1 = cpf + '.';
        document.forms[0].cpf.value = cpf1;
        return true;
    }
    if (cpf1.length === 6){
        cpf2 = cpf1 + '.';
        document.forms[0].cpf1.value = cpf2;
        return true;
    }
    if (cpf2.length === 9){
        cpf3 = cpf2 + '-';
        document.forms[0].cpf2.value = cpf3;
        return true;
    }
}
<!DOCTYPE html>
<html>  
<head>
        <meta charset="UTF-8">
        <title>Placa</title>
</head>
<body>
    <form>
        <p>
        <label>Insira a placa do carro:
        <input type="text" name="placa" id='ehistoai' onkeyup="validarPlaca()" placeholder="ABC-1234" maxlength="14" autofocus>
        </label>
        </p>
    </form>
    <script src="main3.js"></script>
</body>
</html>

So, how can I make sure that, while I am writing the numbers, the dots will appear after the 3rd, 6th, and the hyphen after the 9th number? Thanks for the help!

Advertisement

Answer

w matches any single letter, number or underscore (same as [a-zA-Z0-9_]). You can customize and add only numbers and alphabets using /[a-zA-Z0-9]/g in match function.

Intentionally I’ve used the condition e.key !== "Backspace" && e.key !== "Delete" to not add the characters in input if user use delete or Backspace key.

const naosei = document.getElementById("ehistoai");

naosei.addEventListener(onfocus, validarCPF);

function validarCPF(e) {
  if (e.key !== "Backspace" && e.key !== "Delete") {
    var cpf = naosei.value.match(/w/g) ?? "";
    if (cpf.length >= 3) cpf.splice(3, 0, ".");
    if (cpf.length >= 7) cpf.splice(7, 0, ".");
    if (cpf.length >= 11) cpf.splice(11, 0, "-");
    naosei.value = cpf.join("");
  }
}

naosei.addEventListener("keyup", validarCPF);
<form>
  <p>
    <label>Insira a placa do carro:
                <input type="text" name="placa" id='ehistoai' placeholder="ABC-1234" maxlength="14" autofocus>
            </label>
  </p>
</form>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement