Input Mask

2

I'm having trouble creating a mask for registration input.

Enrollments are made up of 4 or 5 digits, hyphen, 1 digit. (0000? -0).

The mask should be applied as you type input .

But I could not do it using Javascript pure.

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

    
asked by anonymous 07.12.2017 / 21:46

4 answers

2

Using Regular Expression will arrive at the result.

  • \ d Only digits
  • {4,5} 4 to 5 digit limits

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

07.12.2017 / 23:47
0

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

    
07.12.2017 / 22:15
0

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

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

and the function:

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

and then put a if to 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 it is to do so, I also recommend adding a script to decrement the counter if the person clicks the Backspace , or better yet, instead of the counter use .lenght()

    
07.12.2017 / 22:28
0

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>
    
08.12.2017 / 01:16