Make 'Ubmit' button expect action from an Alert?

Asked

Viewed 4,566 times

3

I have an HTML form with a Submit button. Validating the fields at the click of the button, if they are invalid, an alert is displayed, but it disappears quickly and the form already redirects to the action page. It only works when I change the button to button type.

Someone knows how to fix this?

  • 1

    Post the code of your form for us to analyze.

2 answers

2


Not seeing your code gets a little complicated to answer for sure, but I believe it’s because the standard behavior of Submit is being fired.

You can use Event.preventDefault to prevent action default. 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();
  }
}

It is not possible to simulate sending the form in the Stackoverflow snippets, so I put the script in that fiddle.

  • 1

    Thank you so much! Exactly what I wanted.

2

The ideal is to call the validation function on onSubmit form, and if something goes 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>

Browser other questions tagged

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