Input mask

Asked

Viewed 990 times

2

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

Registrations are 4 or 5 digits, hyphen , 1 digit. (0000? -0).

The mask should be applied according to the typing of the input.

But I couldn’t do it using Javascript pure.

The site then does not have jQuery, so I don’t want to have to add the jQuery and a plugin masked for that.

  • So why the tags you don’t want are in the question?

  • @Leocaracciolo was made the edition, I had rejected precisely because to read understood that it has nothing with jQuery, ended up in the end AP approved the edition.

  • @wmsouza, correct, but the question continues with O site então não possui jQuery, entao não quero ter que adicionar o jQuery e um plugin de máscara para isso.

  • Yes, the correct thing is to reverse this issue.

  • was edited. Thanks for the correction :D

4 answers

2


Using Regular Expression will come to the result.

  • \d Digits only
  • {4,5} Limits 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" />

SE6

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

  • It worked, thank you very much :D

  • @Dallingtonaugusto consider marking as Accepted :D

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>

0

I can recommend that instead of you refusing the mask 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

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

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

and the function:

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

and then put a if for when they reach 4 (or 5) digits add a "-" in front. I think with pure Javascript is more or less like this:

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

If you want to do so, I also recommend adding a script to decrease the counter if you click on Backspace, or better yet, instead of the counter use the .lenght()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.