Do 'submit' button wait for an alert action?

3

I have an HTML form with a submit button. Valid the fields in the button click, if these are invalid, an alert is displayed, but this disappears quickly and the form already redirects to the action page. It only works when I change the button type to button.

Does anyone know how to solve this?

    
asked by anonymous 07.11.2015 / 23:44

2 answers

2

Without seeing your code it gets a bit tricky to answer for sure, but I believe it's because the default behavior of submit is being triggered.

You can use Event.preventDefault to prevent default action. After doing the validation, if everything is correct you can use HTMLFormElement.submit() to submit the form.

var input = document.querySelector('input'),
    form = document.querySelector('form');

form.addEventListener('submit', validateAndSubmit, false);

function validateAndSubmit(event) {
  // Prevenindo o comportamento padrão.
  event.preventDefault();

  // Pegando o valor do input.
  var value = input.value;

  // Fazendo a validação e enviando caso esteja OK.
  if (value.length < 5)
    alert('O formulário não será enviado, a palavra não possui 5 caracteres.');

  else {
    alert('O formulário será enviado.');
    form.submit();
  }
}

You can not simulate sending the form in the StackOverflow snippets, so I put the script in this fiddle .

    
08.11.2015 / 00:06
2

Ideally, you should call the validation function in the onSubmit of the form, and if you do something wrong in the validation, return false , so the form is not sent.

function valida() {

  if( ! document.getElementById('nome').value ) {

    alert('Preencha o campo "Nome"');
    return false;
  
  } else {
  
    return true;
    
  }

}
<form action="" method="get" onsubmit="return valida();">
  <input id="nome" type="text"/>
  <br><br>
  <input type="submit" value="Enviar">
</form>
    
08.11.2015 / 00:15