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();
}
});
});
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>