Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
Form validation containing fetch api

I have a simple form which I would like to check has valid data before submitting and saving the data.

However, due to fetch(...) being async, I cannot get the validation to stop and wait for the result.

Is there a way to stop the fetch from being async?
Or is perhaps a better way to do this?

form.addEventListener('submit', (event) => {
    fetch(`/check?id=${id}`)
    .then((res) => res.json())
    .then((json) => {
        if (json.error) {
            // Prevent the submit here
            // event.preventDefault();
        }
    });
});
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

If you want a UI friendly experience you can add onfocusout() or onblur() listeners to each field in the form, and validate each input as they are entered. You can disable the Submit button for the form by default, and only enable it when all validations have passed. Something like this:

function validateId() {
 let id = document.forms.myForm.id.value;
 if(id === ""){
   document.forms.myForm.submit.disabled = true;
   return;
 }
 fetch(`https://api.github.com/users/${id}/repos`)
    .then((res) => res.json())
    .then((json) => {
        if (json.error) {
          // fail validation
          alert("Failed!");
          document.forms.myForm.submit.disabled = true;
        } else {
          // success
          document.forms.myForm.submit.disabled = false;
        }
    })
    .catch(error => {
         alert("Error! " + error);
         document.forms.myForm.submit.disabled = true;
    });
 
}
<form name="myForm" action="/action_page.php" method="post">
  ID: <input type="text" name="id" onfocusout="validateId()">
  <input type="submit" name="submit" value="Submit" disabled>
</form>

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda