Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!