aserrin55
aserrin55

Reputation: 360

Why is submitting the form with if condition false?

I have to make some validations in an HTML form. I do not understand why is the form submitting when one of these two conditions is false. The 'main' function is this:

 var marc = false;
 var dnif = false;

window.addEventListener('submit', function () {
    marc = marcado();
    dnif = nif();
    if(marc && dnif){
        document.getElementById("formm").submit();
    }
}, false);

The methods are these:

function nif() {
  var campo = document.getElementById("dni_id");
  var dni = campo.value;
  numero = dni.substr(0, dni.length - 1);
  let = dni.substr(dni.length - 1, 1);
  numero = numero % 23;
  letra = 'TRWAGMYFPDXBNJZSQVHLCKET';
  letra = letra.substring(numero, numero + 1);
  if (letra !== let) {
    alert('El formato del DNI introducido no es el correcto');
    document.form.dni_id.focus();
    return false;  
  } else {
    return true;
  }


function marcado() {
  if (document.form.terminado.checked) {
    return true;
  } else {
    alert("Debes aceptar los términos y condiciones");
    document.form.terminado.focus();
    return false;
  }
}

The functions are OK. When i tried them with the console they work fine. Then I make the execution of the page and the 'alerts' appear and the returns get false but the form submits.

Any idea? Thanks for the help.

Upvotes: 0

Views: 242

Answers (1)

Alden Be
Alden Be

Reputation: 517

Your current code is a listener attached to form submit, meaning once the form is submitted the code runs, you should instead bind to the button and use on click, and within that code block use event.preventDefault() to prevent automatic html form submission.

Alternatively, you could change the button to type, button instead of submit, and use the html onclick to redirect to your javascript function which handles form submission.

EDIT: I believe I was mistaken, you should be able to still bind to submit, as long as you include, event.preventDefault(); inside your binding, the form should not submit automatically. But either of my other solutions should also work fine.

Upvotes: 1

Related Questions