How to validate field when losing focus?

Asked

Viewed 4,837 times

1

How should I call this validation function PIS input when it loses 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>

1 answer

5


Use the property onblur:

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>

  • Marcelo, Thanks for the help, but I forgot to specify. I need the validation to appear in a Span, below the input, and not in an Alert

  • I edited the answer and added the element span for the display of the message, this is what you want @Karinapinheiro?

  • Exactly that. Thank you!!

Browser other questions tagged

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