Applying JS to Validate Input with Onblur

Asked

Viewed 3,520 times

0

Hello,

I have the following script:

<script>
function TestaCPF(strCPF) {
    var Soma;
    var Resto;
    Soma = 0;
    if (strCPF == "00000000000") return false;

    for (i=1; i<=9; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (11 - i);
    Resto = (Soma * 10) % 11;

    if ((Resto == 10) || (Resto == 11))  Resto = 0;
    if (Resto != parseInt(strCPF.substring(9, 10)) ) return false;

    Soma = 0;
    for (i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (12 - i);
    Resto = (Soma * 10) % 11;

    if ((Resto == 10) || (Resto == 11))  Resto = 0;
    if (Resto != parseInt(strCPF.substring(10, 11) ) ) return false;
    return true;
}
var strCPF = "12345678909";
alert(TestaCPF(strCPF));
</script>

He’s validating the CPF, I’d like to know how to apply in an Input... Ex: Validated? The field turns green... Not validated? Red. I know I have to use the Onblur in the field, but I’m still in doubt how to use it.

2 answers

1


Just call the function from the event onblur of input, as parameter you can pass the own elemento/input, with this to change the color becomes easier.

As follows:

function TestaCPF(elemento) {
  cpf = elemento.value;
  cpf = cpf.replace(/[^\d]+/g, '');
  if (cpf == '') return elemento.style.backgroundColor = "red";
  // Elimina CPFs invalidos conhecidos    
  if (cpf.length != 11 ||
    cpf == "00000000000" ||
    cpf == "11111111111" ||
    cpf == "22222222222" ||
    cpf == "33333333333" ||
    cpf == "44444444444" ||
    cpf == "55555555555" ||
    cpf == "66666666666" ||
    cpf == "77777777777" ||
    cpf == "88888888888" ||
    cpf == "99999999999")
    return elemento.style.backgroundColor = "red";
  // Valida 1o digito 
  add = 0;
  for (i = 0; i < 9; i++)
    add += parseInt(cpf.charAt(i)) * (10 - i);
  rev = 11 - (add % 11);
  if (rev == 10 || rev == 11)
    rev = 0;
  if (rev != parseInt(cpf.charAt(9)))
    return elemento.style.backgroundColor = "red";
  // Valida 2o digito 
  add = 0;
  for (i = 0; i < 10; i++)
    add += parseInt(cpf.charAt(i)) * (11 - i);
  rev = 11 - (add % 11);
  if (rev == 10 || rev == 11)
    rev = 0;
  if (rev != parseInt(cpf.charAt(10)))
   return elemento.style.backgroundColor = "red";
  return elemento.style.backgroundColor = "blue";
}
<input type="text" onblur="TestaCPF(this)">


Detail, I changed your Cpf verification function to another one that is available in: http://www.geradorcpf.com/javascript-validar-cpf.htm because I couldn’t understand your verification code. But it should work the same way if you change your code in the places where you have the return false or true for return elemento.style.backgroundColor = "red/blue";

0

It must work like this:

<input type="text" id="seu_texto" onblur="TestaCPF(this.value);" />

Browser other questions tagged

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