Applying JS to Validate Input with OnBlur

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>

It's validating the CPF, I'd like to know how I apply it in an Input ... Ex: Did you validate? The field turns green ... Not valid? Red. I know I have to use OnBlur in the field, but I'm still in doubt how to use it.

    
asked by anonymous 15.06.2016 / 23:24

2 answers

1

Just call the function from the onblur event of the input , as a parameter you can pass the elemento / input itself, 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've changed your cpf verification function to one that's available at: link because I could not understand your verification code. But it should work the same way if you change your code in places where you have return false or true per return elemento.style.backgroundColor = "red/blue";

    
15.06.2016 / 23:26
0

It should work like this:

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