How to validate field when losing focus?

0

How should I call this PIS validation function in the input when I lose focus?

<script language="javascript" type="text/javascript">
    var ftap = "3298765432";
    var total = 0;
    var i;
    var resto = 0;
    var numPIS = 0;
    var strResto = "";

    function ChecaPIS(pis) {

        total = 0;
        resto = 0;
        numPIS = 0;
        strResto = "";

        numPIS = pis;

        if (numPIS == "" || numPIS == null) {
            return false;
        }

        for (i = 0; i <= 9; i++) {
            resultado = (numPIS.slice(i, i + 1)) * (ftap.slice(i, i + 1));
            total = total + resultado;
        }

        resto = (total % 11)

        if (resto != 0) {
            resto = 11 - resto;
        }

        if (resto == 10 || resto == 11) {
            strResto = resto + "";
            resto = strResto.slice(1, 2);
        }

        if (resto != (numPIS.slice(10, 11))) {
            return false;
        }

        return true;
    }

    function ValidaPis() {
        pis = document.formPis.numPIS.value;

        if (!ChecaPIS(pis)) {
            alert("PIS INVALIDO");
        } else {
            alert("PIS VALIDO");
        }
    }
</script>
    
asked by anonymous 03.04.2017 / 14:10

1 answer

3

Use the onblur property:

var ftap = "3298765432";
var total = 0;
var i;
var resto = 0;
var numPIS = 0;
var strResto = "";

function ChecaPIS(pis) {
  total = 0;
  resto = 0;
  numPIS = 0;
  strResto = "";

  numPIS = pis;

  if (numPIS == "" || numPIS == null) {
    return false;
  }

  for (i = 0; i <= 9; i++) {
    resultado = (numPIS.slice(i, i + 1)) * (ftap.slice(i, i + 1));
    total = total + resultado;
  }

  resto = (total % 11)

  if (resto != 0) {
    resto = 11 - resto;
  }

  if (resto == 10 || resto == 11) {
    strResto = resto + "";
    resto = strResto.slice(1, 2);
  }

  if (resto != (numPIS.slice(10, 11))) {
    return false;
  }

  return true;
}

function ValidaPis(pis) {
  span = document.getElementById("validaPis");

  if (!ChecaPIS(pis)) {
    span.innerHTML="PIS INVALIDO";
  } else {
    span.innerHTML="PIS VALIDO";
  }
}
<input type="text" onBlur="javascript: ValidaPis(this.value);">
<span id="validaPis"></span>
    
03.04.2017 / 14:23