Input for receiving Cpf

Asked

Viewed 508 times

1

Hello I’m new in the javascript field and I’m having a doubt, as I can pick up the value of the keys and block off strings, special characters and only accepts NUMBERS in my field.

My Code to the bottom

<input type="text" id="numero" placeholder="377273288328">
<script>
    let numero = document.getElementById("numero");
    numero.addEventListener("keypress", e=>{
        if(e.keyCode>=48 && e.keyCode<=57){
           // o codigo do 0 ao 9
        }else{
       //como eu bloqueio? 
        }
    })
</script>
  • in the else place e.preventDefault(); to lock the default event by pressing the key

  • William Thank you very much solved my problem.

  • You don’t even need a script for that, just set the field type to number .... <input type="number" id="numero" placeholder="377273288328">

  • I posted an answer on Cpf that validates according to the Federal Revenue rule, that is, only if it is a valid and true Cpf. If you are interested please see https://answall.com/questions/295564/comorvalidar-cpf-com-m%C3%A1scara-em-javascript/295566#295566

2 answers

1


<input type="text" id="numero" placeholder="377273288328">
<script>
    let numero = document.getElementById("numero");
    numero.addEventListener("keypress", e=>{
        if(e.keyCode>=48 && e.keyCode<=57){
           return true;
        }else{
            e.preventDefault();// bloquea o evento padrão ao apertar a tecla
        }
    })
</script>
  • Your answer is correct, but do not answer only with code. Explain a little about what your code is different from the question, otherwise a person who reads your answer might not be able to understand it right away.

0

  • In case it returns false but the input still accepts all character types

Browser other questions tagged

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