Input mask

I'm having trouble creating a mask for license plate input.

The license plates are formed by 4 or 5 digits, hyphen , 1 digit. (0000?-0).

The mask must be applied as you type input.

But I couldn't do it using pure Javascript.

The site then does not have jQuery, so I do not want to have to add the jQuery and a plugin mask for this.

Author: Dallington Augusto, 2017-12-07

4 answers

Using Regular Expression will arrive at the result.

  • \d digits only
  • {4,5} limit 4 to 5 digits

window.onload = function(){
  var campo = document.querySelector('#matricula');
  campo.addEventListener('keyup', function(){
    var matricula = campo.value.replace(/\D/g,""); // Remove o que não é digito
    matricula = matricula.replace(/(\d{4,5})(\d{1})$/,"$1-$2"); // 4 ou 5 dígitos a esquerda e 1 a direita
    console.log(matricula); // Mostra no Console
    this.value = matricula; // Insere o valor formatado no input
    if (campo.value.length < 5) { // Valida
      campo.classList.add("invalido");
    } else {
      campo.classList.remove("invalido");
    }
  });
}
input {
  border: 2px solid #ccc;
  color: #069;
  padding: 8px;
}
.invalido {
  border-color: red;
}
<input type="text" name="matricula" id="matricula" maxlength="7" />

ES6

const maskMatricula = (el) => {
  let matricula = el.value.replace(/\D/g,""); // Remove o que não é digito
  matricula = matricula.replace(/(\d{4,5})(\d{1})$/,"$1-$2"); // 4 ou 5 digitos a esquerda e 1 a direita
  console.log(matricula); // Mostra no Console
  el.value = matricula; // Insere o valor formatado no input
  if (el.value.length < 5) { // Valida
    el.classList.add("invalido");
  } else {
    el.classList.remove("invalido");
  }
}
input {
  border: 2px solid #ccc;
  color: #069;
  padding: 8px;
}
.invalido {
  border-color: red;
}
<input type="text" name="matricula" id="matricula" maxlength="7" onkeyup="maskMatricula(this)" />

References

 2
Author: NoobSaibot, 2020-06-11 14:45:34

I can recommend that instead of you refusing the masks plugin in jquery, you use it but adapting it to pure javascript, it will be easier and compatible with your web, and will also help you create more masks.

 0
Author: Jeferson Santos, 2017-12-07 21:15:49

Without a jQuery,you will need to do everything by hand, which is much more complicated... But you can use onKeyPress to count the digits while typing:

<input type="text" onkeypress="mascara()">

And function:

var count = 0; 
function mascara(){
    count++;
    alert(count);
}

And then put a if so when they reach 4 (or 5) digits add a "-" in front. I think with pure Javascript it looks something like this:

if(count == 5){
        var digitos = document.getElementById('inputComMascara').value;
        alert(digitos);
        document.getElementById('inputComMascara').value = digitos+'-'; 
    }

If you are going to do this, I also recommend that you add a script to decrease the counter if the person clicks the Backspace, or better yet, instead of the counter use .lenght()

 0
Author: Rafa Zanezi, 2017-12-07 21:28:22

Step by step with pure javascript event onkeyup.

function validaMatricula() {
    //retorna valor digitado no input
    var str = document.getElementById("matricula").value;
    //testa se há tracinho na posição permitida
    if((str.indexOf("-")==4)||(str.indexOf("-")==5)){
      //array de strings separados pelo "-" (tracinho)
      var res = str.split("-");
      //verifica se contem somente numeros
      if ((!isNaN(res[0]))&&(!isNaN(res[1]))) {
          //verifica se primeira parte contem 4 ou 5 digitos e
          //se a segunda parte contem 1 digito
          if((res[0].length==4 || res[0].length==5) && (res[1].length==1)){
            document.getElementById("testar").innerText = "Válido";
            document.getElementById('testar').style.backgroundColor = 'blue';
            document.getElementById('testar').style.color = 'white';
          }else{
            document.getElementById("testar").innerText = "Inválido";
            document.getElementById('testar').style.backgroundColor = 'red';
            document.getElementById('testar').style.color = 'yellow';
          }
     }else{
        document.getElementById("testar").innerText = "inválido";
        document.getElementById('testar').style.backgroundColor = 'red';
        document.getElementById('testar').style.color = 'yellow';
    }

  }else{
      document.getElementById("testar").innerText = "inválido";
      document.getElementById('testar').style.backgroundColor = 'red';
      document.getElementById('testar').style.color = 'yellow';
  }

}
<input type="text" onkeyup="validaMatricula()" id="matricula" value="">
<button id="testar">Testar</button>

Step by step with pure javascript event onclick.

function validaMatricula() {
    //retorna valor digitado no input
    var str = document.getElementById("matricula").value;
    //testa se há tracinho na posição permitida
    if((str.indexOf("-")==4)||(str.indexOf("-")==5)){
      //array de strings separados pelo "-" (tracinho)
      var res = str.split("-");
      //verifica se contem somente numeros
      if ((!isNaN(res[0]))&&(!isNaN(res[1]))) {
          //verifica se primeira parte contem 4 ou 5 digitos e
          //se a segunda parte contem 1 digito
          if((res[0].length==4 || res[0].length==5) && (res[1].length==1)){
            document.getElementById("testar").innerText = "Válido";
            document.getElementById('testar').style.backgroundColor = 'blue';
            document.getElementById('testar').style.color = 'white';
          }else{
            document.getElementById("testar").innerText = "Inválido";
            document.getElementById('testar').style.backgroundColor = 'red';
            document.getElementById('testar').style.color = 'yellow';
          }
     }else{
        document.getElementById("testar").innerText = "inválido";
        document.getElementById('testar').style.backgroundColor = 'red';
        document.getElementById('testar').style.color = 'yellow';
    }

  }else{
      document.getElementById("testar").innerText = "inválido";
      document.getElementById('testar').style.backgroundColor = 'red';
      document.getElementById('testar').style.color = 'yellow';
  }

}
<input type="text" id="matricula" value="">
<button id="testar" onclick="validaMatricula()">Testar</button>
 0
Author: Leo Caracciolo, 2017-12-08 10:53:32