I want write a function to prevent any input other than numbers 0-9 and the return key so the user can make corrections. I know that this type of question have been asked several times but why doesn't my code work. Does it has to do with the shift key? Why am I getting "event is not defined"?
In the snippet I can prevent letters but special characters, like @, keep being inserted. Why am I getting a reference error?
// I have two functions
function formatarCPF(event, controle) {
//this line check the returned value from the functions defined below
var eNumero = permitirApenasNumeros(event.keyCode);
if (!eNumero)
event.preventDefault();
if (event.keyCode != 8) {
var valor = controle.value;
if (valor.length == 3) {
controle.value = (controle.value + ".");
}
if (valor.length == 7) {
controle.value = (controle.value + ".");
}
if (valor.length == 11) {
controle.value = (controle.value + "-");
}
}
}
if(event.keyCode != 8) {
var valor = controle.value;
if (valor.length == 0) {
controle.value = "(";
}
if(valor.length == 2) {
controle.value = (controle.value + String.fromCharCode(event.which) + ")");
event.preventDefault();
}
if (valor.length == 9) {
controle.value = (controle.value + "-");
}
}
function permitirApenasNumeros(code) {
//checks to see if the user typed a number
var regex = /[0-9]/;
if(regex.test(String.fromCharCode(code)) || code == 8) {
return true;
} else {
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
<label for="tbCPF">CPF:</label>
<input onkeydown="formatarCPF(event, this)" maxlength="14" placeholder="___.___.___-__" />
</div>
onkeydown="formatarCPF(event, this)"withonkeydown="formatarCPF".